Back to interview questions

100+ Dart Interview Questions and Answers

100+ Dart Interview Questions and Answers

Explore 120 Dart interview questions and answers on types, null safety, collections, generics, asynchronous code, isolates, testing, and runtime behavior.

Explore 120 Dart interview questions and answers on types, null safety, collections, generics, asynchronous code, isolates, testing, and runtime behavior.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

A Dart interview should test whether a developer can reason about types, data, and executionโ€”not just recognize syntax. Useful questions ask candidates to follow a nullable value, choose a collection, explain an asynchronous result, or identify which assumptions change between a native program and a web target.

This guide to 100+ Dart Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It focuses on the Dart language, runtime, core libraries, packages, and testing, using Dart 3.13 as the baseline. Flutter widget lifecycles, layouts, and application state-management frameworks are outside the main scope.

How can recruiters detect AI-assisted cheating, deepfakes, and impersonation during Dart interviews?

Dart interviews often include a small coding exercise, an unfamiliar generic API, or a sequence of futures and stream events to explain. Candidates need to show how they reach an answer and how they handle invalid input or asynchronous failure. Unauthorized real-time assistance can make that independent reasoning harder to assess.

Sherlock AI helps recruiters detect potential AI-assisted cheating, deepfakes, candidate impersonation, and unauthorized real-time assistance during Dart developer interviews.

Pair interview-integrity checks with a short, well-defined problem. Change the input type, introduce a failed future, or switch the stated execution target, then ask the candidate to revise the solution and its tests. Review suspicious activity in context rather than treating a signal as proof of misconduct.

Dart Interview Questions

Choose questions that match the roleโ€™s use of Dart, whether that involves reusable packages, command-line tools, asynchronous services, or web code. State the SDK and execution target before asking about platform-sensitive behavior, and distinguish language reasoning from knowledge of a particular application framework.

Dart Interview Questions for Beginners

These beginner questions cover variables, types, null safety, functions, collections, classes, exceptions, and basic asynchronous code. They test whether a candidate can read a small Dart program and explain its values and control flow.

  1. What is Dart, and how do its native and web targets differ?

  2. How do you write a Dart entry point and read command-line arguments?

  3. How does var differ from an explicitly typed variable and dynamic?

  4. What is the difference between final and const?

  5. Which built-in value and collection types does Dart provide?

  6. How do you parse and convert numbers safely in Dart?

  7. What does sound null safety guarantee in Dart?

  8. How do the null-aware operators differ from the non-null assertion operator?

  9. What does late do, and when can it fail?

  10. When should you use is, is!, and as?

  11. How do division, truncating division, and remainder work in Dart?

  12. How do interpolation, raw strings, and multiline strings work?

  13. Does String.length count user-perceived characters?

  14. How do growable, fixed-length, and unmodifiable lists differ?

  15. How do you choose between a List, Set, and Map?

  16. Why can a map lookup return null even when its value type is non-nullable?

  17. How do collection if, collection for, and spread elements work?

  18. When should you use for, for-in, while, break, and continue?

  19. How does a switch expression differ from a switch statement?

  20. How do you declare a function and use arrow syntax?

  21. How do named, required, optional positional, and default parameters work?

  22. How do first-class functions and closures work in Dart?

  23. How do classes, fields, and instance methods work?

  24. What are unnamed constructors, named constructors, and initializer lists?

  25. How do initializing formals and super parameters reduce constructor boilerplate?

  26. How do static members differ from instance members?

  27. How do inheritance and method overriding work?

  28. How does implementing an interface differ from extending an abstract class?

  29. What problem does a mixin solve?

  30. When are getters and setters useful?

  31. What can an enum contain beyond named constants?

  32. How do generic classes and functions improve type safety?

  33. How do import prefixes, show, and hide control library names?

  34. What does an underscore make private in Dart?

  35. Why are assertions not a substitute for validating external input?

  36. How do on, catch, rethrow, and finally handle failures?

  37. What is a Future, and what do async and await change?

  38. How is a Stream different from a Future, and how does await for consume it?

  39. What do pubspec.yaml, dart pub get, dart analyze, and dart format do?

  40. How would you count the frequency of words in a Dart string?

Dart Interview Questions for Intermediate

These intermediate questions examine generics, patterns, API design, lazy collections, futures, streams, packages, and testing. They ask candidates to preserve a contract when inputs, timing, or platform assumptions become less straightforward.

  1. When should initialization use a constructor, a nullable field, or late final?

  2. How do const constructors affect identity and immutability?

  3. When should you use a factory or redirecting constructor?

  4. How do you implement value equality and a consistent hashCode?

  5. Why is copying a collection not necessarily a deep copy?

  6. How do reified generic types and covariant collections affect runtime checks?

  7. How do generic bounds constrain a reusable API?

  8. When are Iterable transformations lazy, and when are they evaluated?

  9. How do you sort objects with a comparator without relying on a stable sort?

  10. How do fold and reduce behave on empty collections?

  11. How does an unmodifiable snapshot differ from an unmodifiable view?

  12. How are extension methods resolved when static and runtime types differ?

  13. How does an extension type differ from an extension method and a wrapper class?

  14. What do base, interface, final, and sealed restrict across library boundaries?

  15. How can a sealed hierarchy model success and failure exhaustively?

  16. What defines a record's shape, type, and equality?

  17. How do list, map, and object patterns validate and destructure data?

  18. When should you use if-case patterns and when guards?

  19. How do a mixin's on constraint, super calls, and application order interact?

  20. How do typedefs, constructor tear-offs, and callable objects simplify APIs?

  21. How do you validate decoded JSON before constructing a typed model?

  22. How do you serialize a Dart model without assuming every object is JSON-compatible?

  23. How do sync*, async*, yield, and yield* differ?

  24. What order do synchronous code, microtasks, and event-queue tasks run in?

  25. How do you start independent asynchronous operations concurrently and preserve result order?

  26. What do Future.wait's eagerError and cleanUp options actually guarantee?

  27. When does try/catch require return await to intercept a Future failure?

  28. Does Future.timeout cancel the underlying operation?

  29. How do single-subscription and broadcast streams differ?

  30. How do map and asyncMap differ when processing a stream?

  31. Who owns a StreamSubscription, and how should it be paused and canceled?

  32. How do you create and close a StreamController without losing lifecycle control?

  33. How do you read a large text file incrementally on native Dart?

  34. How do you close native file handles reliably when an operation fails?

  35. How do you construct request URIs, handle HTTP status codes, and close an owned client?

  36. How do you write tests for Futures, errors, and streams?

  37. How do dependencies, dev_dependencies, SDK constraints, and lockfiles fit together?

  38. How do analyzer settings and lints enforce stricter typing?

  39. How would you remove duplicates while preserving first-seen order?

  40. How would you group and total records by a key without mutating the input?

Dart Interview Questions for Experienced

These experienced-level questions focus on public API contracts, concurrency boundaries, resource ownership, performance evidence, portability, and evolving a package safely. They assess how a developer makes Dart code reliable when failures and long-lived consumers matter.

  1. How do Object, Object?, dynamic, void, and Never differ in API design?

  2. Why can type promotion fail for fields or captured variables?

  3. How do function subtyping and covariant parameters affect substitutability?

  4. When are self-referential generic bounds useful, and what do they not guarantee?

  5. How do class modifiers change the compatibility promises of a public package?

  6. Why is an extension type not a runtime security or validation boundary?

  7. How do exhaustiveness, guarded patterns, and unreachable cases interact?

  8. How do Future(), Future.microtask(), and Future.sync() schedule work and capture errors?

  9. What can zones intercept, and why can asynchronous errors fail to cross error-zone boundaries?

  10. How do you adapt a callback API with Completer while preventing double completion?

  11. How do you design cooperative cancellation when Future itself has no cancel method?

  12. How would you implement bounded asynchronous concurrency while preserving input order?

  13. How do stream pause, buffering, and cancellation affect backpressure?

  14. How do you design retries with backoff without hiding permanent errors or duplicating side effects?

  15. How can overlapping asynchronous requests produce stale results on a single isolate?

  16. When should CPU-bound work use Isolate.run, and what changes on the web?

  17. Which objects can cross isolate boundaries, and why can captured closures be a problem?

  18. How do you structure a long-lived isolate's request-response protocol and shutdown?

  19. What does TransferableTypedData transfer, and what happens to ownership afterward?

  20. How should a parent isolate observe worker failures and unexpected exits?

  21. How do you profile Dart code without confusing JIT warm-up with AOT performance?

  22. How can a garbage-collected Dart program still retain memory unnecessarily?

  23. How do collection choice and equality behavior affect algorithmic cost?

  24. How do integer precision and bitwise behavior differ between native and JavaScript targets?

  25. What pitfalls arise with floating-point equality, NaN, infinity, and monetary values?

  26. How would you reverse user-perceived characters without splitting surrogate pairs or combining sequences?

  27. Why must UTF-8 be decoded across chunks rather than decoded separately for every byte buffer?

  28. How do conditional imports keep native-only libraries out of web builds?

  29. Why does modern JavaScript interop use static declarations and explicit conversions?

  30. What ownership and ABI rules must a Dart FFI wrapper enforce?

  31. Why is adding a Duration not always the same as advancing a local calendar date?

  32. How do you validate untrusted paths and URLs without confusing parsing with authorization?

  33. How would you parse a compact key-value format with explicit validation and error locations?

  34. How would you implement a capacity-bounded least-recently-used cache?

  35. How would you deduplicate in-flight asynchronous loads without caching failures forever?

  36. How do you design an immutable model that does not leak mutable collection state?

  37. How do a package's SDK lower bound and language version affect new Dart syntax?

  38. How do you make isolate and asynchronous tests deterministic and ensure cleanup?

  39. How do you design a reproducible microbenchmark and avoid unsupported performance claims?

  40. How would you implement a safe asynchronous page iterator with termination and cancellation semantics?

Dart Interview Questions and Answers

The answers follow the question bank in order and connect language rules to concrete behavior. Read each example with its stated imports, package requirements, language version, and target. Some snippets illustrate a narrow rule or an intentional failure rather than a complete application.

Dart Interview Questions and Answers for Beginners

The beginner answers establish the distinctions that affect everyday code: nullable versus non-nullable values, final versus constant data, collection operations, object behavior, and asynchronous results. Examples make the relevant rule explicit rather than relying on memorized output.

1. What is Dart, and how do its native and web targets differ?

Dart is a statically typed, garbage-collected language with type inference, sound null safety, and built-in asynchronous programming support. It can power command-line tools and server programs as well as applications built with Flutter; Flutter is a framework, not another name for Dart.

On native platforms, Dart supports just-in-time execution for development and ahead-of-time compilation to machine code for deployment. Web builds target JavaScript or WebAssembly, with browser-compatible libraries and interoperability constraints. A program using native filesystem APIs cannot simply run unchanged in a browser. Shared business logic should avoid platform-specific dependencies, and deployment choices should account for the target runtime rather than assuming every Dart library works everywhere.

2. How do you write a Dart entry point and read command-line arguments?

A Dart program starts at a top-level main function. A simple application can declare void main(), while a command-line program can accept List<String> arguments. The list contains the arguments supplied to the program, not the Dart executable or source filename. Check its length before indexing and parse values explicitly because every argument arrives as text.

An asynchronous entry point normally uses Future<void> main(...) async. No class wrapper is needed, and dart:core, which provides String, List, and print, is imported automatically. Save this example as greet.dart; invoking dart run greet.dart Ada prints Hello, Ada!. With no argument, it prints the fallback greeting.

Dart example

void main(List<String> arguments) {
  final name = arguments.isEmpty ? 'guest' : arguments.first;
  print('Hello, $name!');
}
void main(List<String> arguments) {
  final name = arguments.isEmpty ? 'guest' : arguments.first;
  print('Hello, $name!');
}
void main(List<String> arguments) {
  final name = arguments.isEmpty ? 'guest' : arguments.first;
  print('Hello, $name!');
}

3. How does var differ from an explicitly typed variable and dynamic?

var asks Dart to infer a variable's static type from its initializer. It does not make the variable dynamically typed: var count = 2 produces an int variable that cannot later hold a string. An explicit annotation states the intended type directly and can deliberately choose a wider type, such as num.

dynamic suppresses many compile-time member checks, moving those checks to runtime. A misspelled method or incompatible assignment can therefore fail only when executed. When a value may have different types but should still be checked before use, Object? is usually a safer boundary type. The example contrasts inferred, explicitly widened, and dynamic variables.

Dart example

void main() {
  var count = 2;
  count += 1;
  num measurement = 2;
  measurement = 2.5;
  dynamic value = 'hello';
  print(value.length); // 5
  value = 7;
  print('$count, $measurement, $value'); // 3, 2.5, 7
  // count = 'three'; // Compile-time error.
}
void main() {
  var count = 2;
  count += 1;
  num measurement = 2;
  measurement = 2.5;
  dynamic value = 'hello';
  print(value.length); // 5
  value = 7;
  print('$count, $measurement, $value'); // 3, 2.5, 7
  // count = 'three'; // Compile-time error.
}
void main() {
  var count = 2;
  count += 1;
  num measurement = 2;
  measurement = 2.5;
  dynamic value = 'hello';
  print(value.length); // 5
  value = 7;
  print('$count, $measurement, $value'); // 3, 2.5, 7
  // count = 'three'; // Compile-time error.
}

4. What is the difference between final and const?

final allows a variable to be assigned once; its value can be computed at runtime. const declares a compile-time constant and also prevents reassignment. A constant expression must use values and operations permitted during constant evaluation, so a current timestamp can be final but not const.

The distinction also concerns the referenced object. A final variable can reference a mutable list, and that list can still change. A constant list cannot change its elements or length. Constant object construction requires a suitable const constructor, and nested values in a constant collection must also be constant. Choose final for stable bindings and const when an actual compile-time constant is appropriate.

Dart example

void main() {
  final names = <String>['Ada'];
  names.add('Lin'); // The list remains mutable.
  const limits = <int>

void main() {
  final names = <String>['Ada'];
  names.add('Lin'); // The list remains mutable.
  const limits = <int>

void main() {
  final names = <String>['Ada'];
  names.add('Lin'); // The list remains mutable.
  const limits = <int>

5. Which built-in value and collection types does Dart provide?

Common Dart types include int and double for numbers, bool for Boolean values, and String for text. Both numeric types are subtypes of num. Object is a non-nullable general object type; Object? also accepts null. Functions are values, and records group multiple positional or named values without requiring a dedicated class.

The main collection types are List<E>, Set<E>, and Map<K, V>. Generic type arguments describe their contents and preserve static checking. A nullable type adds ?, such as String?; this is different from storing the text 'null'. The example combines scalar values, a typed collection, and a record.

Dart example

void main() {
  const int seats = 4;
  const double price = 12.5;
  const bool available = true;
  final List<String> labels = ['window', 'aisle'];
  final Set<int> occupied = {1, 3};
  final Map<String, int> inventory = {'standard': seats};
  final offer = (price: price, available: available);
  print('${labels.first}: ${offer.price}'); // window: 12.5
  print(occupied.contains(2)); // false
  print(inventory['standard']); // 4
}
void main() {
  const int seats = 4;
  const double price = 12.5;
  const bool available = true;
  final List<String> labels = ['window', 'aisle'];
  final Set<int> occupied = {1, 3};
  final Map<String, int> inventory = {'standard': seats};
  final offer = (price: price, available: available);
  print('${labels.first}: ${offer.price}'); // window: 12.5
  print(occupied.contains(2)); // false
  print(inventory['standard']); // 4
}
void main() {
  const int seats = 4;
  const double price = 12.5;
  const bool available = true;
  final List<String> labels = ['window', 'aisle'];
  final Set<int> occupied = {1, 3};
  final Map<String, int> inventory = {'standard': seats};
  final offer = (price: price, available: available);
  print('${labels.first}: ${offer.price}'); // window: 12.5
  print(occupied.contains(2)); // false
  print(inventory['standard']); // 4
}

6. How do you parse and convert numbers safely in Dart?

Use int.tryParse or double.tryParse when malformed text is an expected input condition; they return null instead of throwing FormatException. Successful parsing is only the first validation step. Check domain limits and, for floating-point input, whether the result is finite: strings representing infinity or NaN can parse successfully.

For existing numbers, toDouble() converts to a floating-point value, while toInt() truncates a finite double toward zero rather than rounding. Use round, floor, or ceil when those meanings are intended. Large integer precision can differ on JavaScript targets, so identifiers and exact large quantities require an explicit representation strategy rather than an unchecked conversion to double.

Dart example

int? parseAge(String text) {
  final age = int.tryParse(text.trim());
  if (age == null || age < 0 || age > 130) return null;
  return age;
}

void main() {
  print(parseAge(' 42 ')); // 42
  print(parseAge('unknown')); // null
  print(parseAge('-1')); // null
  print((-3.9).toInt()); // -3
  final amount = double.tryParse('NaN');
  print(amount != null && amount.isFinite); // false
}
int? parseAge(String text) {
  final age = int.tryParse(text.trim());
  if (age == null || age < 0 || age > 130) return null;
  return age;
}

void main() {
  print(parseAge(' 42 ')); // 42
  print(parseAge('unknown')); // null
  print(parseAge('-1')); // null
  print((-3.9).toInt()); // -3
  final amount = double.tryParse('NaN');
  print(amount != null && amount.isFinite); // false
}
int? parseAge(String text) {
  final age = int.tryParse(text.trim());
  if (age == null || age < 0 || age > 130) return null;
  return age;
}

void main() {
  print(parseAge(' 42 ')); // 42
  print(parseAge('unknown')); // null
  print(parseAge('-1')); // null
  print((-3.9).toInt()); // -3
  final amount = double.tryParse('NaN');
  print(amount != null && amount.isFinite); // false
}

7. What does sound null safety guarantee in Dart?

Sound null safety separates nullable types from non-nullable types. A variable declared String cannot successfully contain null, while String? can. The analyzer requires initialization and checks nullable access, so ordinary code must handle absence before using members that need a non-null receiver.

Flow analysis can promote a local variable or parameter after a null check. In the example, returning early when name is null makes it safe to call trim afterward. Null safety does not guarantee a program never throws: !, late, dynamic calls, and casts can still fail when their runtime assumptions are wrong. The guarantee concerns valid values and checked access, not immunity from every programming error.

Dart example

String greeting(String? name) {
  if (name == null) return 'Hello, guest';
  final trimmed = name.trim();
  return trimmed.isEmpty ? 'Hello, guest' : 'Hello, $trimmed';
}

void main() {
  print(greeting(null)); // Hello, guest
  print(greeting(' Ada ')); // Hello, Ada
}
String greeting(String? name) {
  if (name == null) return 'Hello, guest';
  final trimmed = name.trim();
  return trimmed.isEmpty ? 'Hello, guest' : 'Hello, $trimmed';
}

void main() {
  print(greeting(null)); // Hello, guest
  print(greeting(' Ada ')); // Hello, Ada
}
String greeting(String? name) {
  if (name == null) return 'Hello, guest';
  final trimmed = name.trim();
  return trimmed.isEmpty ? 'Hello, guest' : 'Hello, $trimmed';
}

void main() {
  print(greeting(null)); // Hello, guest
  print(greeting(' Ada ')); // Hello, Ada
}

8. How do the null-aware operators differ from the non-null assertion operator?

Null-aware operators provide defined behavior when an operand is null. ?. skips member access on a null receiver, ?? supplies a fallback only for null, and ??= assigns a value only when the current value is null. Null-aware indexing uses ?[], while ...? skips a null collection during a spread.

The postfix ! is different: it asserts that an expression is non-null and throws if that assertion is false. It does not supply a fallback or validate a business rule. Prefer a null check or an appropriate null-aware operation when absence is expected. Also remember that empty strings, zero, and false are not null, so ?? preserves them.

Dart example

String displayName(String? name) => name?.trim() ?? 'Guest';

void main() {
  final cache = <String, String?>{'name': null};
  cache['name'] ??= 'Ada';
  print(displayName(null)); // Guest
  print(displayName('')); // An empty line, not Guest.
  print(cache['name']); // Ada
}
String displayName(String? name) => name?.trim() ?? 'Guest';

void main() {
  final cache = <String, String?>{'name': null};
  cache['name'] ??= 'Ada';
  print(displayName(null)); // Guest
  print(displayName('')); // An empty line, not Guest.
  print(cache['name']); // Ada
}
String displayName(String? name) => name?.trim() ?? 'Guest';

void main() {
  final cache = <String, String?>{'name': null};
  cache['name'] ??= 'Ada';
  print(displayName(null)); // Guest
  print(displayName('')); // An empty line, not Guest.
  print(cache['name']); // Ada
}

9. What does late do, and when can it fail?

late moves an initialization obligation from static analysis to runtime. It is useful when a field must be non-nullable but its value is supplied after construction. Reading an uninitialized late variable throws LateInitializationError; the declaration does not create a default value.

A late variable with an initializer evaluates that initializer lazily on its first read. late final additionally permits only one successful assignment, with invalid subsequent writes rejected statically where provable or checked at runtime. Use these features when the lifecycle genuinely provides the guarantee. If absence is a normal state, a nullable type often models the situation more honestly than a late field whose initialization callers must remember.

Dart example

class Report {
  late final String title;
  late final String heading = title.toUpperCase();
}

void main() {
  final report = Report();
  report.title = 'Quarterly results';
  print(report.heading); // QUARTERLY RESULTS
  // Reading report.title before assignment would fail.
  // Assigning report.title again would fail.
}
class Report {
  late final String title;
  late final String heading = title.toUpperCase();
}

void main() {
  final report = Report();
  report.title = 'Quarterly results';
  print(report.heading); // QUARTERLY RESULTS
  // Reading report.title before assignment would fail.
  // Assigning report.title again would fail.
}
class Report {
  late final String title;
  late final String heading = title.toUpperCase();
}

void main() {
  final report = Report();
  report.title = 'Quarterly results';
  print(report.heading); // QUARTERLY RESULTS
  // Reading report.title before assignment would fail.
  // Assigning report.title again would fail.
}

10. When should you use is, is!, and as?

is tests whether an object satisfies a type, and is! tests the opposite. For a promotable local variable or parameter, a successful test lets subsequent code use the narrower type without an explicit cast. This makes type tests useful at boundaries where values may have several shapes.

as casts a value to a type and throws if it does not match; it is not a numeric conversion or a string parser. Use it when an already-established contract justifies the assumption, not as a substitute for validating uncertain input. A nullable value also fails a cast to a non-nullable type when its actual value is null.

Dart example

String describe(Object? value) {
  if (value is String) return 'Text length: ${value.length}';
  if (value is! num) return 'Not a number';
  return 'Number: $value';
}

void main() {
  print(describe('Dart')); // Text length: 4
  print(describe(null)); // Not a number
  print(describe(12)); // Number: 12
}
String describe(Object? value) {
  if (value is String) return 'Text length: ${value.length}';
  if (value is! num) return 'Not a number';
  return 'Number: $value';
}

void main() {
  print(describe('Dart')); // Text length: 4
  print(describe(null)); // Not a number
  print(describe(12)); // Number: 12
}
String describe(Object? value) {
  if (value is String) return 'Text length: ${value.length}';
  if (value is! num) return 'Not a number';
  return 'Number: $value';
}

void main() {
  print(describe('Dart')); // Text length: 4
  print(describe(null)); // Not a number
  print(describe(12)); // Number: 12
}

11. How do division, truncating division, and remainder work in Dart?

/ performs division and returns a double, even when both operands are integers. ~/ performs truncating division and returns an integer by discarding the fractional part toward zero. This differs from rounding down for negative results: -7 ~/ 3 is -2, not -3.

Dart's % operator computes Euclidean modulo, whose result is nonnegative for a nonzero integer divisor. The remainder() method instead follows truncating division, so a negative dividend can produce a negative remainder. Choosing the wrong operation can break cyclic indexing or signed arithmetic. Validate a divisor before integer division or modulo; do not assume all numeric operations handle division by zero identically.

Dart example

void main() {
  print(7 / 2); // 3.5
  print(7 ~/ 2); // 3
  print(-7 ~/ 3); // -2
  print(-7 % 3); // 2
  print((-7).remainder(3)); // -1
}
void main() {
  print(7 / 2); // 3.5
  print(7 ~/ 2); // 3
  print(-7 ~/ 3); // -2
  print(-7 % 3); // 2
  print((-7).remainder(3)); // -1
}
void main() {
  print(7 / 2); // 3.5
  print(7 ~/ 2); // 3
  print(-7 ~/ 3); // -2
  print(-7 % 3); // 2
  print((-7).remainder(3)); // -1
}

12. How do interpolation, raw strings, and multiline strings work?

Dart supports single-quoted and double-quoted strings with the same semantics. Interpolation inserts a simple variable using $name or evaluates an expression using ${expression}. Values are converted to their string representation, so interpolation is useful for readable messages without manually chaining conversions.

A raw string prefixes the opening quote with r and treats backslashes and dollar signs literally. It is particularly useful for regular expressions and paths. Triple quotes create multiline strings; they do not automatically remove indentation written inside the literal. Normal strings process escapes such as \n, whereas raw strings preserve those characters. Strings themselves are immutable; transformations return new strings.

Dart example

void main() {
  final name = 'Ada';
  final count = 3;
  print('$name has ${count + 1} tasks.'); // Ada has 4 tasks.
  print(r'C:\logs\$name'); // C:\logs\$name
  final message = """First line
Second line""";
  print(message); // Prints the two lines.
}
void main() {
  final name = 'Ada';
  final count = 3;
  print('$name has ${count + 1} tasks.'); // Ada has 4 tasks.
  print(r'C:\logs\$name'); // C:\logs\$name
  final message = """First line
Second line""";
  print(message); // Prints the two lines.
}
void main() {
  final name = 'Ada';
  final count = 3;
  print('$name has ${count + 1} tasks.'); // Ada has 4 tasks.
  print(r'C:\logs\$name'); // C:\logs\$name
  final message = """First line
Second line""";
  print(message); // Prints the two lines.
}

13. Does String.length count user-perceived characters?

No. String.length counts UTF-16 code units, which are neither Unicode code points nor necessarily user-perceived characters. A supplementary code point such as many emoji occupies two code units. A displayed character can also combine several code points, as with a letter followed by a combining accent or an emoji sequence.

runes exposes code points. For user-facing counting and slicing, the characters package works with extended grapheme clusters, which better match perceived characters. Add it to the project's dependencies with dart pub add characters before using the import below. The decomposed accented letter deliberately contains two code points but forms one grapheme cluster; code-unit slicing could split it incorrectly.

Dart example

import 'package:characters/characters.dart';

void main() {
  const text = 'e\u0301'; // e followed by a combining acute accent.
  print(text.length); // 2 UTF-16 code units
  print(text.runes.length); // 2 Unicode code points
  print(text.characters.length); // 1 grapheme cluster
  print('๐Ÿ˜€'.length); // 2 UTF-16 code units
  print('๐Ÿ˜€'.runes.length); // 1 Unicode code point
}
import 'package:characters/characters.dart';

void main() {
  const text = 'e\u0301'; // e followed by a combining acute accent.
  print(text.length); // 2 UTF-16 code units
  print(text.runes.length); // 2 Unicode code points
  print(text.characters.length); // 1 grapheme cluster
  print('๐Ÿ˜€'.length); // 2 UTF-16 code units
  print('๐Ÿ˜€'.runes.length); // 1 Unicode code point
}
import 'package:characters/characters.dart';

void main() {
  const text = 'e\u0301'; // e followed by a combining acute accent.
  print(text.length); // 2 UTF-16 code units
  print(text.runes.length); // 2 Unicode code points
  print(text.characters.length); // 1 grapheme cluster
  print('๐Ÿ˜€'.length); // 2 UTF-16 code units
  print('๐Ÿ˜€'.runes.length); // 1 Unicode code point
}

14. How do growable, fixed-length, and unmodifiable lists differ?

A growable list allows element replacement and length changes through operations such as add and remove. A fixed-length list allows replacement of existing elements but rejects changes to its length. An unmodifiable list rejects both replacement and structural changes.

These are properties of the list object, not of whether its variable is declared final. List.unmodifiable makes an unmodifiable list containing the supplied elements; later structural changes to the source list do not change that result. This protection is shallow: mutable objects stored inside can still change. The example separates a growable source, a fixed-size buffer, and an unmodifiable snapshot so their different update rules are visible.

Dart example

void main() {
  final growable = <int>[1, 2];
  final fixed = List<int>.filled(2, 0);
  final snapshot = List<int>

void main() {
  final growable = <int>[1, 2];
  final fixed = List<int>.filled(2, 0);
  final snapshot = List<int>

void main() {
  final growable = <int>[1, 2];
  final fixed = List<int>.filled(2, 0);
  final snapshot = List<int>

15. How do you choose between a List, Set, and Map?

Use a List when positions, repeated values, and sequence order matter. Use a Set when membership and uniqueness are the primary concerns. Use a Map to associate unique keys with values, such as product codes with stock counts. Assigning an existing map key replaces its value rather than adding a duplicate key.

The type alone does not promise one ordering policy for every implementation. Standard literal sets and maps preserve insertion order, while specialized sorted or hash collections can have different iteration behavior. Equality also determines uniqueness and key matching. An empty {} is a map by default; write <String>{} or provide a Set<String> context to create an empty set.

Dart example

void main() {
  final visits = <String>['home', 'search', 'home'];
  final uniquePages = visits.toSet();
  final stock = <String, int>{'book'

void main() {
  final visits = <String>['home', 'search', 'home'];
  final uniquePages = visits.toSet();
  final stock = <String, int>{'book'

void main() {
  final visits = <String>['home', 'search', 'home'];
  final uniquePages = visits.toSet();
  final stock = <String, int>{'book'

16. Why can a map lookup return null even when its value type is non-nullable?

For a Map<K, V>, the indexing operator returns V? because the requested key might be absent. Consequently, a lookup in Map<String, int> has type int?, even though stored values cannot be null. The result's nullability describes a potentially missing entry, not permission to store null in that map.

Use ?? when absence has a meaningful default, or save the lookup in a local variable and check it before use. If the map permits nullable values, a null lookup cannot distinguish an absent key from a key explicitly associated with null; use containsKey for that distinction. Avoid ! unless the key's existence is genuinely guaranteed.

Dart example

void main() {
  final counts = <String, int>{'dart': 2};
  final count = counts['flutter'];
  print(count); // null
  print(counts['dart'] ?? 0); // 2
  final notes = <String, String?>{'draft': null};
  print(notes['draft']); // null
  print(notes.containsKey('draft')); // true
  print(notes.containsKey('missing')); // false
}
void main() {
  final counts = <String, int>{'dart': 2};
  final count = counts['flutter'];
  print(count); // null
  print(counts['dart'] ?? 0); // 2
  final notes = <String, String?>{'draft': null};
  print(notes['draft']); // null
  print(notes.containsKey('draft')); // true
  print(notes.containsKey('missing')); // false
}
void main() {
  final counts = <String, int>{'dart': 2};
  final count = counts['flutter'];
  print(count); // null
  print(counts['dart'] ?? 0); // 2
  final notes = <String, String?>{'draft': null};
  print(notes['draft']); // null
  print(notes.containsKey('draft')); // true
  print(notes.containsKey('missing')); // false
}

17. How do collection if, collection for, and spread elements work?

Collection elements let a literal express how its contents are built. An if element conditionally includes an element, while a for element produces elements from an iterable. A spread element, written ..., inserts the contents of another collection rather than nesting that collection as a single item.

Use ...? when the collection being spread may be null; it contributes nothing in that case. Spreading is shallow and does not clone the objects inside. Lists and sets spread iterable elements, while maps spread map entries. These features compose, so a loop can contain a condition. The example builds a label list while filtering empty input and optionally including extra labels.

Dart example

List<String> labelsFor(List<String> names, {List<String>? extras}) {
  return [
    'People',
    if (names.isEmpty) 'None',
    for (final name in names)
      if (name.isNotEmpty) '@$name',
    ...?extras,
  ];
}

void main() {
  print(labelsFor(['Ada', ''], extras: ['Done']));
  // [People, @Ada, Done]
  print(labelsFor([])); // [People, None]
}
List<String> labelsFor(List<String> names, {List<String>? extras}) {
  return [
    'People',
    if (names.isEmpty) 'None',
    for (final name in names)
      if (name.isNotEmpty) '@$name',
    ...?extras,
  ];
}

void main() {
  print(labelsFor(['Ada', ''], extras: ['Done']));
  // [People, @Ada, Done]
  print(labelsFor([])); // [People, None]
}
List<String> labelsFor(List<String> names, {List<String>? extras}) {
  return [
    'People',
    if (names.isEmpty) 'None',
    for (final name in names)
      if (name.isNotEmpty) '@$name',
    ...?extras,
  ];
}

void main() {
  print(labelsFor(['Ada', ''], extras: ['Done']));
  // [People, @Ada, Done]
  print(labelsFor([])); // [People, None]
}

18. When should you use for, for-in, while, break, and continue?

Use a traditional for loop when an index or explicitly controlled update is important. Use for-in to visit iterable elements without managing an index. A while loop repeats while its condition is true, and a do-while loop checks afterward, so its body executes at least once.

break leaves the enclosing loop; continue skips the remainder of the current iteration and proceeds to the next one. These are useful for early termination and filtering, but the loop must still make progress. Avoid structural changes to an ordinary collection while iterating it. The example skips negative entries and stops at a sentinel instead of processing every value.

Dart example

void main() {
  var total = 0;
  for (final value in [3, -1, 5, 0, 100]) {
    if (value == 0) break;
    if (value < 0) continue;
    total += value;
  }
  print(total); // 8
  var remaining = 2;
  while (remaining > 0) {
    print(remaining); // 2, then 1
    remaining--;
  }
}
void main() {
  var total = 0;
  for (final value in [3, -1, 5, 0, 100]) {
    if (value == 0) break;
    if (value < 0) continue;
    total += value;
  }
  print(total); // 8
  var remaining = 2;
  while (remaining > 0) {
    print(remaining); // 2, then 1
    remaining--;
  }
}
void main() {
  var total = 0;
  for (final value in [3, -1, 5, 0, 100]) {
    if (value == 0) break;
    if (value < 0) continue;
    total += value;
  }
  print(total); // 8
  var remaining = 2;
  while (remaining > 0) {
    print(remaining); // 2, then 1
    remaining--;
  }
}

19. How does a switch expression differ from a switch statement?

A switch statement chooses a block of statements to execute. A switch expression evaluates to a value, making it convenient for assignments and return expressions. Its arms use pattern => expression without the case keyword, and it must cover every possible input value. A wildcard _ can provide a fallback when the input type is open-ended.

Both forms support pattern matching in modern Dart. Nonempty switch-statement cases do not implicitly fall through to the next case, so a routine terminating break is unnecessary. Use a statement for multi-step actions and an expression for a compact value mapping. The enum example is exhaustive without a wildcard, allowing missing cases to be detected if the enum grows.

Dart example

enum DeliveryState { queued, sent, failed }

String label(DeliveryState state) => switch (state) {
  DeliveryState.queued => 'Waiting',
  DeliveryState.sent => 'Delivered',
  DeliveryState.failed => 'Retry needed',
};

void main() {
  print(label(DeliveryState.sent)); // Delivered
  switch (DeliveryState.failed) {
    case DeliveryState.failed:
      print('Notify support');
    default:
      print('No action');
  }
}
enum DeliveryState { queued, sent, failed }

String label(DeliveryState state) => switch (state) {
  DeliveryState.queued => 'Waiting',
  DeliveryState.sent => 'Delivered',
  DeliveryState.failed => 'Retry needed',
};

void main() {
  print(label(DeliveryState.sent)); // Delivered
  switch (DeliveryState.failed) {
    case DeliveryState.failed:
      print('Notify support');
    default:
      print('No action');
  }
}
enum DeliveryState { queued, sent, failed }

String label(DeliveryState state) => switch (state) {
  DeliveryState.queued => 'Waiting',
  DeliveryState.sent => 'Delivered',
  DeliveryState.failed => 'Retry needed',
};

void main() {
  print(label(DeliveryState.sent)); // Delivered
  switch (DeliveryState.failed) {
    case DeliveryState.failed:
      print('Notify support');
    default:
      print('No action');
  }
}

20. How do you declare a function and use arrow syntax?

A function declaration specifies a name, parameter list, and body, with an optional explicit return-type annotation. Declaring the return and parameter types makes a public contract clear and helps analysis catch incorrect calls. A block body can contain multiple statements and uses return to provide a result; void indicates that callers should not use a returned value.

Arrow syntax, => expression, is a concise form for a single expression. It does not accept a sequence of statements or an if statement, although a conditional expression is valid. Choose the form that keeps the implementation readable rather than compressing complex branching into one line. Both functions below have explicit, checked signatures.

Dart example

int square(int value) => value * value;

int absoluteDifference(int left, int right) {
  final difference = left - right;
  return difference.abs();
}

void main() {
  print(square(5)); // 25
  print(absoluteDifference(3, 8)); // 5
}
int square(int value) => value * value;

int absoluteDifference(int left, int right) {
  final difference = left - right;
  return difference.abs();
}

void main() {
  print(square(5)); // 25
  print(absoluteDifference(3, 8)); // 5
}
int square(int value) => value * value;

int absoluteDifference(int left, int right) {
  final difference = left - right;
  return difference.abs();
}

void main() {
  print(square(5)); // 25
  print(absoluteDifference(3, 8)); // 5
}

21. How do named, required, optional positional, and default parameters work?

Required positional parameters appear first and are supplied by position. Optional positional parameters use square brackets, while named parameters use braces and are supplied as name: value. A function can have required positional parameters followed by either optional positional parameters or named parameters, but not both optional groups.

Named parameters are optional unless marked required. Requiredness and nullability are independent: required String? note must be supplied but can receive null. Optional parameters need either a nullable type or a compatible default value, and defaults must be compile-time constants. Named arguments improve clarity when several values have similar types; optional positional arguments suit small, familiar signatures.

Dart example

String greet({required String name, String prefix = 'Hello'}) {
  return '$prefix, $name';
}

int addOffset(int value, [int offset = 1]) => value + offset;

void main() {
  print(greet(name: 'Ada')); // Hello, Ada
  print(greet(name: 'Lin', prefix: 'Welcome')); // Welcome, Lin
  print(addOffset(4)); // 5
  print(addOffset(4, 3)); // 7
}
String greet({required String name, String prefix = 'Hello'}) {
  return '$prefix, $name';
}

int addOffset(int value, [int offset = 1]) => value + offset;

void main() {
  print(greet(name: 'Ada')); // Hello, Ada
  print(greet(name: 'Lin', prefix: 'Welcome')); // Welcome, Lin
  print(addOffset(4)); // 5
  print(addOffset(4, 3)); // 7
}
String greet({required String name, String prefix = 'Hello'}) {
  return '$prefix, $name';
}

int addOffset(int value, [int offset = 1]) => value + offset;

void main() {
  print(greet(name: 'Ada')); // Hello, Ada
  print(greet(name: 'Lin', prefix: 'Welcome')); // Welcome, Lin
  print(addOffset(4)); // 5
  print(addOffset(4, 3)); // 7
}

22. How do first-class functions and closures work in Dart?

Functions are first-class values: they can be stored, passed to other functions, and returned. A precise function type such as int Function(int) documents the accepted arguments and result more clearly than the broad Function type. A method or function name without parentheses can provide a tear-off instead of invoking it immediately.

A closure retains access to variables in its lexical scope after the surrounding function has returned. It captures the variables, not merely frozen copies of their initial values. This makes factories for callbacks and small stateful functions possible, but shared captured state can also introduce surprising coupling. Each call to the factory below creates a separate captured counter.

Dart example

int Function() makeCounter() {
  var count = 0;
  return () => ++count;
}

void main() {
  final first = makeCounter();
  final second = makeCounter();
  print(first()); // 1
  print(first()); // 2
  print(second()); // 1
  final doubled = [1, 2, 3].map((value) => value * 2).toList();
  print(doubled); // [2, 4, 6]
}
int Function() makeCounter() {
  var count = 0;
  return () => ++count;
}

void main() {
  final first = makeCounter();
  final second = makeCounter();
  print(first()); // 1
  print(first()); // 2
  print(second()); // 1
  final doubled = [1, 2, 3].map((value) => value * 2).toList();
  print(doubled); // [2, 4, 6]
}
int Function() makeCounter() {
  var count = 0;
  return () => ++count;
}

void main() {
  final first = makeCounter();
  final second = makeCounter();
  print(first()); // 1
  print(first()); // 2
  print(second()); // 1
  final doubled = [1, 2, 3].map((value) => value * 2).toList();
  print(doubled); // [2, 4, 6]
}

23. How do classes, fields, and instance methods work?

A class defines the state and behavior of its instances. Fields store per-object data, constructors establish initial state, and instance methods operate on a particular receiver. Access members with a dot, such as counter.increment(). Within a method, this refers to the current object, though it is usually omitted when no name conflict exists.

Different instances normally have separate field values. A final field cannot be reassigned after initialization, while a mutable field can change as methods run. Keeping mutation behind meaningful methods can protect invariants and make callers easier to understand. The example creates two counters to demonstrate that changing one instance does not change the other.

Dart example

class Counter {
  int value;
  Counter(this.value);

  void increment() {
    value++;
  }
}

void main() {
  final first = Counter(0);
  final second = Counter(10);
  first.increment();
  print(first.value); // 1
  print(second.value); // 10
}
class Counter {
  int value;
  Counter(this.value);

  void increment() {
    value++;
  }
}

void main() {
  final first = Counter(0);
  final second = Counter(10);
  first.increment();
  print(first.value); // 1
  print(second.value); // 10
}
class Counter {
  int value;
  Counter(this.value);

  void increment() {
    value++;
  }
}

void main() {
  final first = Counter(0);
  final second = Counter(10);
  first.increment();
  print(first.value); // 1
  print(second.value); // 10
}

24. What are unnamed constructors, named constructors, and initializer lists?

An unnamed constructor uses the class name, while a named constructor adds a descriptive suffix such as Point.origin. Named constructors provide distinct construction paths; they are not ordinary methods and are not inherited by subclasses. If a class declares no constructor, Dart provides an unnamed, no-argument default constructor when the superclass requirements allow it.

An initializer list follows a colon and initializes fields before the constructor body executes. It is useful for derived values and non-nullable final fields that must be initialized before the object is usable. Initializer expressions cannot access this. The example has a normal construction path, an origin path, and a path that transforms input coordinates before storing them.

Dart example

class Point {
  final double x;
  final double y;

  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  Point.scaled(double x, double y, double factor)
      : x = x * factor,
        y = y * factor;
}

void main() {
  final origin = Point.origin();
  final scaled = Point.scaled(2, 3, 4);
  print('${origin.x}, ${origin.y}'); // 0.0, 0.0
  print('${scaled.x}, ${scaled.y}'); // 8.0, 12.0
}
class Point {
  final double x;
  final double y;

  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  Point.scaled(double x, double y, double factor)
      : x = x * factor,
        y = y * factor;
}

void main() {
  final origin = Point.origin();
  final scaled = Point.scaled(2, 3, 4);
  print('${origin.x}, ${origin.y}'); // 0.0, 0.0
  print('${scaled.x}, ${scaled.y}'); // 8.0, 12.0
}
class Point {
  final double x;
  final double y;

  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  Point.scaled(double x, double y, double factor)
      : x = x * factor,
        y = y * factor;
}

void main() {
  final origin = Point.origin();
  final scaled = Point.scaled(2, 3, 4);
  print('${origin.x}, ${origin.y}'); // 0.0, 0.0
  print('${scaled.x}, ${scaled.y}'); // 8.0, 12.0
}

25. How do initializing formals and super parameters reduce constructor boilerplate?

An initializing formal, such as this.name, declares a constructor parameter that directly initializes an instance field. Its type can be inferred from that field, eliminating a separate parameter and assignment in the initializer list. This is especially useful for final fields, which must be initialized before a generative constructor's body runs.

A super parameter, such as super.name, forwards an argument to the corresponding superclass constructor parameter. It reduces boilerplate without creating another field in the subclass or inheriting the superclass constructor itself. Named super parameters are also supported. When calling a named superclass constructor, an explicit superclass initializer can select that constructor while super parameters forward the appropriate values.

Dart example

class Person {
  final String name;
  Person(this.name);
}

class Employee extends Person {
  final int employeeId;
  Employee(super.name, this.employeeId);
}

void main() {
  final employee = Employee('Ada', 42);
  print('${employee.name}: ${employee.employeeId}'); // Ada: 42
}
class Person {
  final String name;
  Person(this.name);
}

class Employee extends Person {
  final int employeeId;
  Employee(super.name, this.employeeId);
}

void main() {
  final employee = Employee('Ada', 42);
  print('${employee.name}: ${employee.employeeId}'); // Ada: 42
}
class Person {
  final String name;
  Person(this.name);
}

class Employee extends Person {
  final int employeeId;
  Employee(super.name, this.employeeId);
}

void main() {
  final employee = Employee('Ada', 42);
  print('${employee.name}: ${employee.employeeId}'); // Ada: 42
}

26. How do static members differ from instance members?

An instance member belongs to a particular object and can access that object's fields through this. A static member belongs to the class namespace and is accessed using the class name. Static methods have no receiver, so they cannot directly use instance fields or this; they need an explicit object if they require instance data.

Static fields are useful for class-wide constants or deliberately shared state, but mutable global-style state can make tests and lifecycle management harder. In Dart, ordinary static field state is also local to its isolate rather than shared mutable memory across isolates. A static utility is appropriate only when the operation does not naturally belong to a particular instance.

Dart example

class Ticket {
  static const String prefix = 'T';
  final int number;
  Ticket(this.number);

  String get label => '$prefix-$number';
  static bool isValidNumber(int value) => value > 0;
}

void main() {
  print(Ticket.prefix); // T
  print(Ticket.isValidNumber(7)); // true
  print(Ticket(7).label); // T-7
}
class Ticket {
  static const String prefix = 'T';
  final int number;
  Ticket(this.number);

  String get label => '$prefix-$number';
  static bool isValidNumber(int value) => value > 0;
}

void main() {
  print(Ticket.prefix); // T
  print(Ticket.isValidNumber(7)); // true
  print(Ticket(7).label); // T-7
}
class Ticket {
  static const String prefix = 'T';
  final int number;
  Ticket(this.number);

  String get label => '$prefix-$number';
  static bool isValidNumber(int value) => value > 0;
}

void main() {
  print(Ticket.prefix); // T
  print(Ticket.isValidNumber(7)); // true
  print(Ticket(7).label); // T-7
}

27. How do inheritance and method overriding work?

A class uses extends to inherit implementation from one superclass. It can add members or override inherited methods, getters, and setters with compatible declarations. The @override annotation communicates intent and helps the analyzer identify mistakes, but the annotation itself does not create overriding behavior.

Calls to instance members use the actual object's implementation, even when the variable has a superclass type. An override must remain usable wherever the original contract is expected; narrowing accepted parameters can violate that substitutability. Use super to invoke inherited behavior when extending rather than replacing it. Constructors are handled separately and are not inherited. Composition is often preferable when the relationship is reuse without a genuine subtype relationship.

Dart example

class Animal {
  String speak() => 'sound';
}

class Dog extends Animal {
  @override
  String speak() => 'woof';
}

void main() {
  final Animal animal = Dog();
  print(animal.speak()); // woof
}
class Animal {
  String speak() => 'sound';
}

class Dog extends Animal {
  @override
  String speak() => 'woof';
}

void main() {
  final Animal animal = Dog();
  print(animal.speak()); // woof
}
class Animal {
  String speak() => 'sound';
}

class Dog extends Animal {
  @override
  String speak() => 'woof';
}

void main() {
  final Animal animal = Dog();
  print(animal.speak()); // woof
}

28. How does implementing an interface differ from extending an abstract class?

Every class introduces an implicit interface describing its instance members. implements adopts a contract without inheriting its method bodies or field storage, so a concrete implementer must supply all required instance members, including those that were concrete in the original class.

extends inherits available implementation from a single superclass. An abstract class cannot be instantiated directly but can provide fields, constructors, concrete methods, and abstract members for subclasses to complete. A class can implement multiple interfaces. Modern class modifiers can restrict these relationships across library boundaries, so an API's declaration matters. In this example, the subclass inherits summary, while the implementing class must define its own version.

Dart example

abstract class Greeter {
  String greet();
  String summary() => 'Greeting: ${greet()}';
}

class FriendlyGreeter extends Greeter {
  @override
  String greet() => 'Hello';
}

class BriefGreeter implements Greeter {
  @override
  String greet() => 'Hi';
  @override
  String summary() => greet();
}

void main() {
  print(FriendlyGreeter().summary()); // Greeting: Hello
  print(BriefGreeter().summary()); // Hi
}
abstract class Greeter {
  String greet();
  String summary() => 'Greeting: ${greet()}';
}

class FriendlyGreeter extends Greeter {
  @override
  String greet() => 'Hello';
}

class BriefGreeter implements Greeter {
  @override
  String greet() => 'Hi';
  @override
  String summary() => greet();
}

void main() {
  print(FriendlyGreeter().summary()); // Greeting: Hello
  print(BriefGreeter().summary()); // Hi
}
abstract class Greeter {
  String greet();
  String summary() => 'Greeting: ${greet()}';
}

class FriendlyGreeter extends Greeter {
  @override
  String greet() => 'Hello';
}

class BriefGreeter implements Greeter {
  @override
  String greet() => 'Hi';
  @override
  String summary() => greet();
}

void main() {
  print(FriendlyGreeter().summary()); // Greeting: Hello
  print(BriefGreeter().summary()); // Hi
}

29. What problem does a mixin solve?

A mixin packages member implementations for reuse across otherwise unrelated class hierarchies. Apply it with with rather than forcing every consumer to inherit from a shared base class. A mixin can define fields and methods, and it can declare abstract members that the applying class must provide.

An on constraint can require a suitable superclass and enable appropriate super calls. Mixins do not declare generative constructors, so dependencies often arrive through abstract getters or methods. They are useful for cohesive reusable behavior, but applying several overlapping mixins can make method resolution less obvious. The example requires a label from the host class and supplies reusable message formatting.

Dart example

mixin TaggedMessages {
  String get tag;
  String formatMessage(String message) => '[$tag] $message';
}

class ImportJob with TaggedMessages {
  @override
  final String tag;
  ImportJob(this.tag);
}

void main() {
  final job = ImportJob('catalog');
  print(job.formatMessage('Started')); // [catalog] Started
}
mixin TaggedMessages {
  String get tag;
  String formatMessage(String message) => '[$tag] $message';
}

class ImportJob with TaggedMessages {
  @override
  final String tag;
  ImportJob(this.tag);
}

void main() {
  final job = ImportJob('catalog');
  print(job.formatMessage('Started')); // [catalog] Started
}
mixin TaggedMessages {
  String get tag;
  String formatMessage(String message) => '[$tag] $message';
}

class ImportJob with TaggedMessages {
  @override
  final String tag;
  ImportJob(this.tag);
}

void main() {
  final job = ImportJob('catalog');
  print(job.formatMessage('Started')); // [catalog] Started
}

30. When are getters and setters useful?

Getters and setters expose property syntax while allowing computed values or controlled access to stored state. A getter can derive a value rather than storing redundant data, and a setter can validate an update before changing a backing field. Ordinary fields already provide implicit accessors, so explicit accessors are useful when they add meaningful behavior.

Keep property access unsurprising: expensive asynchronous work usually deserves a method returning a future rather than a deceptively simple property. Validation should use ordinary checks, not assertions that may be disabled. The temperature example keeps Celsius as its source of truth, derives Fahrenheit, and rejects updates below absolute zero without corrupting the previously stored value.

Dart example

class Temperature {
  double _celsius = 0;

  double get celsius => _celsius;
  set celsius(double value) {
    if (!value.isFinite || value < -273.15) {
      throw ArgumentError.value(value, 'value', 'Invalid temperature');
    }
    _celsius = value;
  }

  double get fahrenheit => _celsius * 9 / 5 + 32;
}

void main() {
  final temperature = Temperature();
  temperature.celsius = 100;
  print(temperature.fahrenheit); // 212.0
}
class Temperature {
  double _celsius = 0;

  double get celsius => _celsius;
  set celsius(double value) {
    if (!value.isFinite || value < -273.15) {
      throw ArgumentError.value(value, 'value', 'Invalid temperature');
    }
    _celsius = value;
  }

  double get fahrenheit => _celsius * 9 / 5 + 32;
}

void main() {
  final temperature = Temperature();
  temperature.celsius = 100;
  print(temperature.fahrenheit); // 212.0
}
class Temperature {
  double _celsius = 0;

  double get celsius => _celsius;
  set celsius(double value) {
    if (!value.isFinite || value < -273.15) {
      throw ArgumentError.value(value, 'value', 'Invalid temperature');
    }
    _celsius = value;
  }

  double get fahrenheit => _celsius * 9 / 5 + 32;
}

void main() {
  final temperature = Temperature();
  temperature.celsius = 100;
  print(temperature.fahrenheit); // 212.0
}

31. What can an enum contain beyond named constants?

An enum represents a fixed set of named instances, and enhanced enums can attach fields, getters, methods, and constructors to those instances. This keeps behavior associated with each option instead of maintaining unrelated lookup tables or repeated switches. Instance fields must be final, and generative constructors must be constant.

Enums provide values, index, and name. The index follows declaration order, so persisting it as a durable external identifier is fragile when values are reordered. Prefer an explicit stable code when storage or a protocol requires one. Enums cannot override equality, hashCode, or index, and cannot be freely instantiated outside their declared instances. The example associates a label and urgency rule with each priority.

Dart example

enum Priority {
  low('Low', 10),
  high('High', 20);

  final String label;
  final int code;
  const Priority(this.label, this.code);

  bool get isUrgent => this == Priority.high;
}

void main() {
  print(Priority.high.label); // High
  print(Priority.high.isUrgent); // true
  print(Priority.values.length); // 2
}
enum Priority {
  low('Low', 10),
  high('High', 20);

  final String label;
  final int code;
  const Priority(this.label, this.code);

  bool get isUrgent => this == Priority.high;
}

void main() {
  print(Priority.high.label); // High
  print(Priority.high.isUrgent); // true
  print(Priority.values.length); // 2
}
enum Priority {
  low('Low', 10),
  high('High', 20);

  final String label;
  final int code;
  const Priority(this.label, this.code);

  bool get isUrgent => this == Priority.high;
}

void main() {
  print(Priority.high.label); // High
  print(Priority.high.isUrgent); // true
  print(Priority.values.length); // 2
}

32. How do generic classes and functions improve type safety?

Generics express a relationship between types while allowing one implementation to work with many concrete types. A Box<String> stores a string and returns a string without callers casting from Object or relying on dynamic. Generic functions similarly preserve the connection between their arguments and result.

A bound such as T extends num restricts acceptable type arguments and permits operations available on the bound. Dart retains generic type information at runtime, so checks can distinguish types such as List<int> and List<String>. Generics do not eliminate every runtime check, but they catch many incompatible uses earlier. The example shows a reusable container and a function that preserves its caller's selected type.

Dart example

class Box<T> {
  final T value;
  Box(this.value);
}

T choose<T>(bool takeFirst, T first, T second) {
  return takeFirst ? first : second;
}

void main() {
  final box = Box<String>('Dart');
  final result = choose<int>(true, 4, 9);
  print(box.value.toUpperCase()); // DART
  print(result + 1); // 5
}
class Box<T> {
  final T value;
  Box(this.value);
}

T choose<T>(bool takeFirst, T first, T second) {
  return takeFirst ? first : second;
}

void main() {
  final box = Box<String>('Dart');
  final result = choose<int>(true, 4, 9);
  print(box.value.toUpperCase()); // DART
  print(result + 1); // 5
}
class Box<T> {
  final T value;
  Box(this.value);
}

T choose<T>(bool takeFirst, T first, T second) {
  return takeFirst ? first : second;
}

void main() {
  final box = Box<String>('Dart');
  final result = choose<int>(true, 4, 9);
  print(box.value.toUpperCase()); // DART
  print(result + 1); // 5
}

33. How do import prefixes, show, and hide control library names?

An import prefix introduced with as places imported declarations behind a qualifier, which helps disambiguate names from different libraries. A show combinator imports only listed names, while hide excludes listed names. These mechanisms affect names available through that import; they do not rename the underlying declarations or change their accessibility in the original library.

Use dart: for SDK libraries and package: for package libraries. Import directives belong before declarations. Prefixes can also make the source of a utility obvious without importing every name unqualified. The example imports only sqrt from dart:math behind a prefix. An alternative unprefixed import could hide a conflicting name, but it should not be added redundantly here.

Dart example

import 'dart:math' as math show sqrt;

void main() {
  print(math.sqrt(81)); // 9.0
}
import 'dart:math' as math show sqrt;

void main() {
  print(math.sqrt(81)); // 9.0
}
import 'dart:math' as math show sqrt;

void main() {
  print(math.sqrt(81)); // 9.0
}

34. What does an underscore make private in Dart?

A leading underscore makes a declaration private to its library, not merely to its class. Other classes and top-level functions in the same library can access that declaration. A separate Dart file normally defines a separate library, while files connected with part and part of share the library and its private names.

This differs from Java-style class-private fields and from package-wide privacy: being in the same package does not automatically grant access. Use a public method or getter when another library needs controlled access. The example intentionally places a top-level helper beside the class, so it can read the private field. Moving that helper into an importing library would make the access invalid.

Dart example

class Vault {
  final String _secret;
  Vault(this._secret);

  int get secretLength => _secret.length;
}

// This function is in the same library as Vault.
bool hasSecret(Vault vault) => vault._secret.isNotEmpty;

void main() {
  final vault = Vault('sample');
  print(hasSecret(vault)); // true
  print(vault.secretLength); // 6
}
class Vault {
  final String _secret;
  Vault(this._secret);

  int get secretLength => _secret.length;
}

// This function is in the same library as Vault.
bool hasSecret(Vault vault) => vault._secret.isNotEmpty;

void main() {
  final vault = Vault('sample');
  print(hasSecret(vault)); // true
  print(vault.secretLength); // 6
}
class Vault {
  final String _secret;
  Vault(this._secret);

  int get secretLength => _secret.length;
}

// This function is in the same library as Vault.
bool hasSecret(Vault vault) => vault._secret.isNotEmpty;

void main() {
  final vault = Vault('sample');
  print(hasSecret(vault)); // true
  print(vault.secretLength); // 6
}

35. Why are assertions not a substitute for validating external input?

Assertions document assumptions and catch programming mistakes when assertions are enabled. Their conditions and optional messages are not evaluated when assertions are disabled, so they cannot enforce input constraints in every deployment. Code must also avoid putting required side effects inside an assertion.

External input needs ordinary control flow that always runs: check the value and throw an appropriate exception, return a validation result, or reject the request. Assertions can supplement those checks by expressing internal invariants, but should not replace them. The parser below rejects malformed, zero, and negative quantities regardless of assertion settings, then uses an assertion only to restate an invariant already established by the real validation.

Dart example

int parseQuantity(String text) {
  final quantity = int.tryParse(text);
  if (quantity == null || quantity <= 0) {
    throw FormatException('Quantity must be a positive integer');
  }
  assert(quantity > 0);
  return quantity;
}

void main() {
  print(parseQuantity('3')); // 3
  try {
    parseQuantity('0');
  } on FormatException {
    print('Invalid quantity'); // Invalid quantity
  }
}
int parseQuantity(String text) {
  final quantity = int.tryParse(text);
  if (quantity == null || quantity <= 0) {
    throw FormatException('Quantity must be a positive integer');
  }
  assert(quantity > 0);
  return quantity;
}

void main() {
  print(parseQuantity('3')); // 3
  try {
    parseQuantity('0');
  } on FormatException {
    print('Invalid quantity'); // Invalid quantity
  }
}
int parseQuantity(String text) {
  final quantity = int.tryParse(text);
  if (quantity == null || quantity <= 0) {
    throw FormatException('Quantity must be a positive integer');
  }
  assert(quantity > 0);
  return quantity;
}

void main() {
  print(parseQuantity('3')); // 3
  try {
    parseQuantity('0');
  } on FormatException {
    print('Invalid quantity'); // Invalid quantity
  }
}

36. How do on, catch, rethrow, and finally handle failures?

A try block encloses operations that may fail. An on clause matches an exception type, while catch binds the thrown object and optionally its stack trace. Clauses are considered in order, so more specific handlers should precede broad ones. Dart does not require functions to declare their possible exceptions.

Use rethrow inside a handler when the same failure should continue outward while preserving its original stack trace. A finally block runs as control leaves the protected operation, making it appropriate for cleanup. Avoid returning or throwing unnecessarily from cleanup because that can hide an earlier outcome. The example records a failed parse, performs cleanup-style bookkeeping, and lets the caller choose the user-facing response.

Dart example

int parseLogged(String source) {
  try {
    return int.parse(source);
  } on FormatException {
    print('Could not parse $source');
    rethrow;
  } finally {
    print('Parse attempt finished');
  }
}

void main() {
  try {
    parseLogged('x');
  } on FormatException catch (error) {
    print('Enter digits only (${error.runtimeType})');
  }
  // Output order: failure notice, finished notice, caller response.
}
int parseLogged(String source) {
  try {
    return int.parse(source);
  } on FormatException {
    print('Could not parse $source');
    rethrow;
  } finally {
    print('Parse attempt finished');
  }
}

void main() {
  try {
    parseLogged('x');
  } on FormatException catch (error) {
    print('Enter digits only (${error.runtimeType})');
  }
  // Output order: failure notice, finished notice, caller response.
}
int parseLogged(String source) {
  try {
    return int.parse(source);
  } on FormatException {
    print('Could not parse $source');
    rethrow;
  } finally {
    print('Parse attempt finished');
  }
}

void main() {
  try {
    parseLogged('x');
  } on FormatException catch (error) {
    print('Enter digits only (${error.runtimeType})');
  }
  // Output order: failure notice, finished notice, caller response.
}

37. What is a Future, and what do async and await change?

A Future<T> represents a computation that can complete at most once with either a value of type T or an error. An async function returns a future, allowing callers to observe completion even though its body is written in a sequential style. await suspends that function until the awaited result is available; it does not block the entire isolate.

Asynchronous syntax does not automatically move CPU-heavy work to another thread. Synchronous work inside an async function still occupies the current isolate until it yields. Handle awaited failures with ordinary try and catch, and avoid discarding futures whose completion or errors matter. The example awaits a simulated lookup before using its string result.

Dart example

import 'dart:async';

Future<String> loadName() async {
  await Future<void>.delayed(const Duration(milliseconds: 10));
  return 'Ada';
}

Future<void> main() async {
  print('Loading');
  final name = await loadName();
  print('Hello, $name');
  // Output order: Loading, then Hello, Ada.
}
import 'dart:async';

Future<String> loadName() async {
  await Future<void>.delayed(const Duration(milliseconds: 10));
  return 'Ada';
}

Future<void> main() async {
  print('Loading');
  final name = await loadName();
  print('Hello, $name');
  // Output order: Loading, then Hello, Ada.
}
import 'dart:async';

Future<String> loadName() async {
  await Future<void>.delayed(const Duration(milliseconds: 10));
  return 'Ada';
}

Future<void> main() async {
  print('Loading');
  final name = await loadName();
  print('Hello, $name');
  // Output order: Loading, then Hello, Ada.
}

38. How is a Stream different from a Future, and how does await for consume it?

A future describes one eventual completion, while a Stream<T> delivers a sequence of asynchronous data events, possible error events, and a done event. Streams fit repeated values such as file chunks or incoming updates. An await for loop consumes data events sequentially inside an async function and continues after the stream closes normally.

If the stream produces an error, the loop exits with that error unless handled outside the loop. Leaving the loop with break cancels its subscription. A stream that never closes can keep the loop waiting indefinitely, so lifecycle expectations matter. The finite example consumes three values and prints only after their stream has completed.

Dart example

import 'dart:async';

Future<void> main() async {
  final values = Stream<int>.fromIterable([2, 4, 6]);
  var total = 0;
  await for (final value in values) {
    total += value;
  }
  print(total); // 12
}
import 'dart:async';

Future<void> main() async {
  final values = Stream<int>.fromIterable([2, 4, 6]);
  var total = 0;
  await for (final value in values) {
    total += value;
  }
  print(total); // 12
}
import 'dart:async';

Future<void> main() async {
  final values = Stream<int>.fromIterable([2, 4, 6]);
  var total = 0;
  await for (final value in values) {
    total += value;
  }
  print(total); // 12
}

39. What do pubspec.yaml, dart pub get, dart analyze, and dart format do?

pubspec.yaml describes a Dart package, including its name, SDK constraint, dependencies, and optional metadata. dart pub get resolves and downloads compatible dependencies and generates package-resolution data; it is not a compiler or test runner. The lockfile records resolved versions, with applications normally committing it for reproducibility.

dart analyze performs static analysis, including type checks and configured lints. dart format rewrites source layout according to Dart formatting rules; formatting success does not establish program correctness. Run these from the package root as part of a broader workflow that also includes tests. The minimal package declaration below targets the Dart 3.13 family and later compatible Dart 3 releases without claiming any dependency is installed here.

YAML example

name: interview_examples
publish_to: 'none'
environment:
  sdk: '>=3.13.0 <4.0.0'
name: interview_examples
publish_to: 'none'
environment:
  sdk: '>=3.13.0 <4.0.0'
name: interview_examples
publish_to: 'none'
environment:
  sdk: '>=3.13.0 <4.0.0'

Shell command

dart pub get

dart pub get

dart pub get

40. How would you count the frequency of words in a Dart string?

Define tokenization before counting. This implementation treats a word as ASCII letters with an optional internal straight apostrophe, lowercases the input, and ignores punctuation and digits. That means Dart and dart share a key, while don't remains one token. Empty or punctuation-only input naturally produces an empty map.

For each regular-expression match, increment the map entry or initialize it to one. The algorithm scans the normalized text and uses expected constant-time map updates; memory includes the normalized string and distinct word keys. This is an intentionally limited English-style tokenizer, not a universal Unicode word segmenter. Languages with different boundaries, curly apostrophes, or locale-sensitive case rules require an explicit alternative policy.

Dart example

Map<String, int> wordFrequencies(String text) {
  final counts = <String, int>{};
  final pattern = RegExp(r"[a-z]+(?:'[a-z]+)?");
  for (final match in pattern.allMatches(text.toLowerCase())) {
    final word = match.group(0)!;
    counts[word] = (counts[word] ?? 0) + 1;
  }
  return counts;
}

void main() {
  print(wordFrequencies("Dart, dart! Don't stop; don't."));
  // {dart: 2, don't: 2, stop: 1}
  print(wordFrequencies('... 123')); // {}
}
Map<String, int> wordFrequencies(String text) {
  final counts = <String, int>{};
  final pattern = RegExp(r"[a-z]+(?:'[a-z]+)?");
  for (final match in pattern.allMatches(text.toLowerCase())) {
    final word = match.group(0)!;
    counts[word] = (counts[word] ?? 0) + 1;
  }
  return counts;
}

void main() {
  print(wordFrequencies("Dart, dart! Don't stop; don't."));
  // {dart: 2, don't: 2, stop: 1}
  print(wordFrequencies('... 123')); // {}
}
Map<String, int> wordFrequencies(String text) {
  final counts = <String, int>{};
  final pattern = RegExp(r"[a-z]+(?:'[a-z]+)?");
  for (final match in pattern.allMatches(text.toLowerCase())) {
    final word = match.group(0)!;
    counts[word] = (counts[word] ?? 0) + 1;
  }
  return counts;
}

void main() {
  print(wordFrequencies("Dart, dart! Don't stop; don't."));
  // {dart: 2, don't: 2, stop: 1}
  print(wordFrequencies('... 123')); // {}
}

Dart Interview Questions and Answers for Intermediate

The intermediate answers explain implementation choices through their type, error, lifecycle, and resource implications. They separate asynchronous scheduling from parallel work and distinguish a useful abstraction from a runtime guarantee.

41. When should initialization use a constructor, a nullable field, or late final?

Use constructor initialization for a value every valid instance must have immediately. It makes the requirement visible to callers and lets the analyzer enforce initialization. Use a nullable field when absence is a meaningful state, rather than merely an inconvenient initialization order. Use late final when a non-null value genuinely becomes available later and is assigned once, or when its initializer should run lazily.

late shifts checks to runtime: reading before assignment fails, and assigning an already initialized late final fails. A constructor is therefore safer when possible. Here, configuration is required, the nickname is optional, and activation supplies the token later.

Dart example

class Session {
  final String endpoint;
  String? nickname;
  late final String token;
  Session(this.endpoint);
  void activate(String value) => token = value;
}

void main() {
  final session = Session('https://example.com');
  print(session.nickname); // null
  session.activate('demo-token');
  print(session.token); // demo-token
}
class Session {
  final String endpoint;
  String? nickname;
  late final String token;
  Session(this.endpoint);
  void activate(String value) => token = value;
}

void main() {
  final session = Session('https://example.com');
  print(session.nickname); // null
  session.activate('demo-token');
  print(session.token); // demo-token
}
class Session {
  final String endpoint;
  String? nickname;
  late final String token;
  Session(this.endpoint);
  void activate(String value) => token = value;
}

void main() {
  final session = Session('https://example.com');
  print(session.nickname); // null
  session.activate('demo-token');
  print(session.token); // demo-token
}

42. How do const constructors affect identity and immutability?

A const constructor permits constant instances; calling that constructor without a constant context still creates an ordinary instance. Equivalent constant expressions are canonicalized, so identical can be true for separately written constants. That is different from overriding == to provide value equality.

A class with a const constructor must have final instance fields, including inherited fields. However, final references alone do not make every instance deeply immutable: a non-constant invocation can receive a mutable list. A constant invocation requires constant-compatible arguments, preventing that mutable list from entering the constant object. Use immutable field types or defensive copies when non-constant callers also need strong immutability guarantees.

Dart example

class Tags {
  final List<String> values;
  const Tags(this.values);
}

void main() {
  const a = Tags(['dart']);
  const b = Tags(['dart']);
  print(identical(a, b)); // true
  final mutable = Tags(<String>

class Tags {
  final List<String> values;
  const Tags(this.values);
}

void main() {
  const a = Tags(['dart']);
  const b = Tags(['dart']);
  print(identical(a, b)); // true
  final mutable = Tags(<String>

class Tags {
  final List<String> values;
  const Tags(this.values);
}

void main() {
  const a = Tags(['dart']);
  const b = Tags(['dart']);
  print(identical(a, b)); // true
  final mutable = Tags(<String>

43. When should you use a factory or redirecting constructor?

Use a factory when construction needs to return a cached object, select a subtype, or perform work before deciding which instance to return. A factory does not have an instance this, must return an appropriate non-null instance, and does not necessarily allocate a new object.

A redirecting generative constructor delegates to another constructor in the same class, keeping field initialization in one place. A redirecting factory can instead name another class's constructor, which is useful for hiding an implementation behind an API. The example combines a validating named factory with a redirecting convenience constructor; validation uses an exception rather than an assertion that production execution might disable.

Dart example

class Port {
  final int number;
  Port._(this.number);
  Port.https() : this._(443);

  factory Port.checked(int number) {
    if (number < 1 || number > 65535) {
      throw RangeError.range(number, 1, 65535, 'number');
    }
    return Port._(number);
  }
}

void main() {
  print(Port.https().number); // 443
  print(Port.checked(8080).number); // 8080
}
class Port {
  final int number;
  Port._(this.number);
  Port.https() : this._(443);

  factory Port.checked(int number) {
    if (number < 1 || number > 65535) {
      throw RangeError.range(number, 1, 65535, 'number');
    }
    return Port._(number);
  }
}

void main() {
  print(Port.https().number); // 443
  print(Port.checked(8080).number); // 8080
}
class Port {
  final int number;
  Port._(this.number);
  Port.https() : this._(443);

  factory Port.checked(int number) {
    if (number < 1 || number > 65535) {
      throw RangeError.range(number, 1, 65535, 'number');
    }
    return Port._(number);
  }
}

void main() {
  print(Port.https().number); // 443
  print(Port.checked(8080).number); // 8080
}

44. How do you implement value equality and a consistent hashCode?

Override == and hashCode together, using the same logical fields. Equal objects must have equal hash codes; equal hash codes do not prove equality. Equality should be reflexive, symmetric, and transitive, and it must handle objects of unrelated types safely.

Prefer immutable equality fields for keys stored in a Map or members stored in a Set. Changing a field that contributes to a stored key's hash can make lookups fail. Object.hash combines fields without requiring a hand-written hashing algorithm. This value type checks runtimeType to avoid accidentally equating a future subtype that might introduce additional state; identity remains a separate question.

Dart example

final class Coordinate {
  final int x;
  final int y;
  const Coordinate(this.x, this.y);

  @override
  bool operator ==(Object other) =>
      other is Coordinate &&
      other.runtimeType == runtimeType && x == other.x && y == other.y;

  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  final points = {Coordinate(2, 3), Coordinate(2, 3)};
  print(points.length); // 1
}
final class Coordinate {
  final int x;
  final int y;
  const Coordinate(this.x, this.y);

  @override
  bool operator ==(Object other) =>
      other is Coordinate &&
      other.runtimeType == runtimeType && x == other.x && y == other.y;

  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  final points = {Coordinate(2, 3), Coordinate(2, 3)};
  print(points.length); // 1
}
final class Coordinate {
  final int x;
  final int y;
  const Coordinate(this.x, this.y);

  @override
  bool operator ==(Object other) =>
      other is Coordinate &&
      other.runtimeType == runtimeType && x == other.x && y == other.y;

  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  final points = {Coordinate(2, 3), Coordinate(2, 3)};
  print(points.length); // 1
}

45. Why is copying a collection not necessarily a deep copy?

A spread, List.of, or toList creates a new outer collection but normally preserves references to its elements. Appending to the copy does not append to the original; mutating a shared inner list can still affect both. An unmodifiable outer collection also does not freeze mutable elements.

A deep copy needs an explicit policy for the domain: which objects are immutable and shareable, which must be cloned, and whether cycles or repeated references must be preserved. For a list of integer lists, copying each inner list is sufficient because integers are immutable. JSON encode/decode is not a universal cloning strategy because it loses unsupported types and identity relationships.

Dart example

void main() {
  final original = <List<int>>[[1, 2]];
  final shallow = List<List<int>>.of(original);
  final deep = [for (final row in original) List<int>.of(row)];
  shallow.first.add(3);
  deep.first.add(4);
  print(original); // [[1, 2, 3]]
  print(deep); // [[1, 2, 4]]
  print(identical(original, shallow)); // false
}
void main() {
  final original = <List<int>>[[1, 2]];
  final shallow = List<List<int>>.of(original);
  final deep = [for (final row in original) List<int>.of(row)];
  shallow.first.add(3);
  deep.first.add(4);
  print(original); // [[1, 2, 3]]
  print(deep); // [[1, 2, 4]]
  print(identical(original, shallow)); // false
}
void main() {
  final original = <List<int>>[[1, 2]];
  final shallow = List<List<int>>.of(original);
  final deep = [for (final row in original) List<int>.of(row)];
  shallow.first.add(3);
  deep.first.add(4);
  print(original); // [[1, 2, 3]]
  print(deep); // [[1, 2, 4]]
  print(identical(original, shallow)); // false
}

46. How do reified generic types and covariant collections affect runtime checks?

Dart preserves generic type information at runtime, so a check such as value is List<int> can distinguish an integer list from a string list. Generic types are covariant: a List<int> can be used where List<num> is expected because int is a subtype of num.

That assignment does not convert the underlying object into a list that accepts every number. Writes still obey its actual element type, so inserting a double through the wider reference throws a runtime type error. If the consumer must add arbitrary numbers, create a genuinely new List<num>. For read-only APIs, accepting Iterable<num> can avoid exposing mutation operations, though it is not an immutability guarantee.

Dart example

void main() {
  final integers = <int>[1, 2];
  List<num> alias = integers;
  print(alias is List<int>); // true
  try {
    alias.add(2.5);
  } on TypeError {
    print('Rejected double'); // Rejected double
  }
  final numbers = List<num>

void main() {
  final integers = <int>[1, 2];
  List<num> alias = integers;
  print(alias is List<int>); // true
  try {
    alias.add(2.5);
  } on TypeError {
    print('Rejected double'); // Rejected double
  }
  final numbers = List<num>

void main() {
  final integers = <int>[1, 2];
  List<num> alias = integers;
  print(alias is List<int>); // true
  try {
    alias.add(2.5);
  } on TypeError {
    print('Rejected double'); // Rejected double
  }
  final numbers = List<num>

47. How do generic bounds constrain a reusable API?

A bound such as T extends num restricts acceptable type arguments and allows the implementation to use members guaranteed by that bound. A bound is a capability requirement, not a runtime conversion. T extends Object excludes nullable type arguments, whereas an unconstrained type parameter has the nullable upper bound Object?.

Self-referential bounds such as T extends Comparable<T> describe operations involving the same type. The generic maximum function below returns the original element type and defines an explicit empty-input failure. Its bound accepts strings and suitable domain types. It does not mean every superficially comparable type necessarily implements Comparable with exactly its own type argument.

Dart example

T maximum<T extends Comparable<T>>(Iterable<T> values) {
  final iterator = values.iterator;
  if (!iterator.moveNext()) throw StateError('No values');
  var result = iterator.current;
  while (iterator.moveNext()) {
    if (iterator.current.compareTo(result) > 0) {
      result = iterator.current;
    }
  }
  return result;
}

void main() {
  print(maximum<String>(['pear', 'apple', 'plum'])); // plum
}
T maximum<T extends Comparable<T>>(Iterable<T> values) {
  final iterator = values.iterator;
  if (!iterator.moveNext()) throw StateError('No values');
  var result = iterator.current;
  while (iterator.moveNext()) {
    if (iterator.current.compareTo(result) > 0) {
      result = iterator.current;
    }
  }
  return result;
}

void main() {
  print(maximum<String>(['pear', 'apple', 'plum'])); // plum
}
T maximum<T extends Comparable<T>>(Iterable<T> values) {
  final iterator = values.iterator;
  if (!iterator.moveNext()) throw StateError('No values');
  var result = iterator.current;
  while (iterator.moveNext()) {
    if (iterator.current.compareTo(result) > 0) {
      result = iterator.current;
    }
  }
  return result;
}

void main() {
  print(maximum<String>(['pear', 'apple', 'plum'])); // plum
}

48. When are Iterable transformations lazy, and when are they evaluated?

Transformations such as map and where generally produce lazy iterables: callbacks run when a consumer requests elements, not when the transformation is declared. Operations such as toList, fold, or a for loop consume those elements. Short-circuiting consumers can stop before visiting the entire input.

A lazy iterable is not automatically memoized. Iterating it again can execute callbacks again and observe changes to the source collection. Materialize a snapshot when repeated work or changing input would be undesirable, and keep transformation callbacks free of surprising side effects. The counter below deliberately exposes evaluation timing; in production, its side effect would usually belong outside the transformation.

Dart example

void main() {
  var calls = 0;
  final doubled = [1, 2, 3].map((value) {
    calls++;
    return value * 2;
  });
  print(calls); // 0
  print(doubled.first); // 2
  print(calls); // 1
  final snapshot = doubled.toList();
  print(snapshot); // [2, 4, 6]
  print(calls); // 4
}
void main() {
  var calls = 0;
  final doubled = [1, 2, 3].map((value) {
    calls++;
    return value * 2;
  });
  print(calls); // 0
  print(doubled.first); // 2
  print(calls); // 1
  final snapshot = doubled.toList();
  print(snapshot); // [2, 4, 6]
  print(calls); // 4
}
void main() {
  var calls = 0;
  final doubled = [1, 2, 3].map((value) {
    calls++;
    return value * 2;
  });
  print(calls); // 0
  print(doubled.first); // 2
  print(calls); // 1
  final snapshot = doubled.toList();
  print(snapshot); // [2, 4, 6]
  print(calls); // 4
}

49. How do you sort objects with a comparator without relying on a stable sort?

List.sort mutates the list and does not guarantee a stable sort. If a comparator returns zero for two different items, their original relative order is not guaranteed. Comparators must be consistent: negative means before, zero means equivalent for ordering, and positive means after.

Add meaningful secondary keys for deterministic ordering. When the requirement specifically preserves input order among equal primary keys, decorate each item with its original index and use that index as the tie-breaker. Sorting a copied or decorated list avoids mutating the caller's input. Prefer compareTo over subtracting numeric keys, and define a separate policy if keys can be null.

Dart example

void main() {
  final rows = [(name: 'B', score: 2), (name: 'A', score: 1),
    (name: 'C', score: 2)];
  final indexed = rows.indexed.toList();
  indexed.sort((a, b) {
    final byScore = a.$2.score.compareTo(b.$2.score);
    return byScore != 0 ? byScore : a.$1.compareTo(b.$1);
  });
  final sorted = indexed.map((entry) => entry.$2).toList();
  print(sorted.map((row) => row.name).join(',')); // A,B,C
  print(rows.first.name); // B: original list is unchanged
}
void main() {
  final rows = [(name: 'B', score: 2), (name: 'A', score: 1),
    (name: 'C', score: 2)];
  final indexed = rows.indexed.toList();
  indexed.sort((a, b) {
    final byScore = a.$2.score.compareTo(b.$2.score);
    return byScore != 0 ? byScore : a.$1.compareTo(b.$1);
  });
  final sorted = indexed.map((entry) => entry.$2).toList();
  print(sorted.map((row) => row.name).join(',')); // A,B,C
  print(rows.first.name); // B: original list is unchanged
}
void main() {
  final rows = [(name: 'B', score: 2), (name: 'A', score: 1),
    (name: 'C', score: 2)];
  final indexed = rows.indexed.toList();
  indexed.sort((a, b) {
    final byScore = a.$2.score.compareTo(b.$2.score);
    return byScore != 0 ? byScore : a.$1.compareTo(b.$1);
  });
  final sorted = indexed.map((entry) => entry.$2).toList();
  print(sorted.map((row) => row.name).join(',')); // A,B,C
  print(rows.first.name); // B: original list is unchanged
}

50. How do fold and reduce behave on empty collections?

reduce uses the first element as its initial accumulator and therefore throws StateError for an empty iterable. Its result has the element type. fold receives an explicit starting value and can use a different accumulator type; an empty iterable returns that starting value unchanged.

Choose an identity that matches the operation: zero for addition and one for multiplication. An arbitrary default can hide missing-data errors, so an empty maximum or average may deserve a nullable result or an exception instead. The example demonstrates both empty summation and reducing string lengths into an integer, without forcing callers to manufacture a dummy first element.

Dart example

void main() {
  final empty = <int>[];
  print(empty.fold<int>(0, (sum, n) => sum + n)); // 0
  try {
    empty.reduce((a, b) => a + b);
  } on StateError {
    print('No seed'); // No seed
  }
  final letters = ['Dart', 'API'].fold<int>

void main() {
  final empty = <int>[];
  print(empty.fold<int>(0, (sum, n) => sum + n)); // 0
  try {
    empty.reduce((a, b) => a + b);
  } on StateError {
    print('No seed'); // No seed
  }
  final letters = ['Dart', 'API'].fold<int>

void main() {
  final empty = <int>[];
  print(empty.fold<int>(0, (sum, n) => sum + n)); // 0
  try {
    empty.reduce((a, b) => a + b);
  } on StateError {
    print('No seed'); // No seed
  }
  final letters = ['Dart', 'API'].fold<int>

51. How does an unmodifiable snapshot differ from an unmodifiable view?

List.unmodifiable captures the elements present when it is constructed and prevents structural changes through the resulting list. UnmodifiableListView instead exposes an existing list through a read-only interface, so later changes to the backing list remain visible.

Neither choice recursively freezes the elements. If the elements are mutable objects, callers may still change their state. A view is useful for exposing live internal state without granting list mutation, while a snapshot is better for a stable handoff or comparison. Avoid promising deep immutability unless the element types and ownership rules support it. Both operations differ from a final list variable, which only prevents reassignment.

Dart example

import 'dart:collection';

void main() {
  final source = <int>[1];
  final snapshot = List<int>.unmodifiable(source);
  final view = UnmodifiableListView<int>(source);
  source.add(2);
  print(snapshot); // [1]
  print(view); // [1, 2]
  try {
    view.add(3);
  } on UnsupportedError {
    print('Read-only')

import 'dart:collection';

void main() {
  final source = <int>[1];
  final snapshot = List<int>.unmodifiable(source);
  final view = UnmodifiableListView<int>(source);
  source.add(2);
  print(snapshot); // [1]
  print(view); // [1, 2]
  try {
    view.add(3);
  } on UnsupportedError {
    print('Read-only')

import 'dart:collection';

void main() {
  final source = <int>[1];
  final snapshot = List<int>.unmodifiable(source);
  final view = UnmodifiableListView<int>(source);
  source.add(2);
  print(snapshot); // [1]
  print(view); // [1, 2]
  try {
    view.add(3);
  } on UnsupportedError {
    print('Read-only')

52. How are extension methods resolved when static and runtime types differ?

Extension methods are selected using the receiver's static type and the extensions in scope, not the runtime class of the object. An applicable instance member takes precedence over an extension member with the same name. A dynamic receiver uses dynamic member lookup, which does not discover extension methods.

If multiple visible extensions are equally applicable, resolve the ambiguity with an explicit extension override, an import prefix, or import filtering. Extensions add convenient syntax without modifying the underlying class or enabling virtual overrides. In this example, both variables reference strings, but their static types select different extensions. Naming the extension explicitly can request a particular implementation.

Dart example

extension ObjectLabel on Object {
  String label() => 'object';
}
extension StringLabel on String {
  String label() => 'string';
}

void main() {
  Object broad = 'hello';
  String narrow = 'hello';
  print(broad.label()); // object
  print(narrow.label()); // string
  print(ObjectLabel(narrow).label()); // object
}
extension ObjectLabel on Object {
  String label() => 'object';
}
extension StringLabel on String {
  String label() => 'string';
}

void main() {
  Object broad = 'hello';
  String narrow = 'hello';
  print(broad.label()); // object
  print(narrow.label()); // string
  print(ObjectLabel(narrow).label()); // object
}
extension ObjectLabel on Object {
  String label() => 'object';
}
extension StringLabel on String {
  String label() => 'string';
}

void main() {
  Object broad = 'hello';
  String narrow = 'hello';
  print(broad.label()); // object
  print(narrow.label()); // string
  print(ObjectLabel(narrow).label()); // object
}

53. How does an extension type differ from an extension method and a wrapper class?

An extension method adds statically resolved operations to an existing type without defining a new runtime object. An extension type provides a distinct compile-time interface over a representation value. It can expose selected operations while avoiding a separate wrapper allocation; its distinction is erased at runtime.

A wrapper class, by contrast, is a genuine runtime object with its own identity and runtime type, and can store additional state. Extension types are useful for compile-time domain distinctions or interop, but are not a runtime security or validation boundary: casts and dynamic interactions operate on the representation. Validate untrusted data separately rather than assuming the static type proves that validation occurred.

Dart example

extension type CustomerId(int value) {
  String get display => 'C-$value';
}

void main() {
  final id = CustomerId(42);
  print(id.display); // C-42
  print(id.value); // 42
  Object runtimeValue = id;
  print(runtimeValue is int); // true
  // id + 1; // Compile-time error: '+' is not exposed.
}
extension type CustomerId(int value) {
  String get display => 'C-$value';
}

void main() {
  final id = CustomerId(42);
  print(id.display); // C-42
  print(id.value); // 42
  Object runtimeValue = id;
  print(runtimeValue is int); // true
  // id + 1; // Compile-time error: '+' is not exposed.
}
extension type CustomerId(int value) {
  String get display => 'C-$value';
}

void main() {
  final id = CustomerId(42);
  print(id.display); // C-42
  print(id.value); // 42
  Object runtimeValue = id;
  print(runtimeValue is int); // true
  // id + 1; // Compile-time error: '+' is not exposed.
}

54. What do base, interface, final, and sealed restrict across library boundaries?

These modifiers express how another library may build on a class; declarations in the defining library have more freedom. A base subtype must itself be marked base, final, or sealed, preserving inherited implementation guarantees. A final class also carries the base restrictions for its subtypes. sealed is implicitly abstract and enables exhaustive analysis of its direct subtype family.

Modifier

Extend from another library

Implement from another library

base

Yes, with required subtype modifier

No

interface

No

Yes

final

No

No

sealed

No

No

The two-file example permits inheritance but rejects external implementation. Restrictions are per library, not simply per directory.

Dart example

// vehicle.dart
base class Vehicle {
  String move() => 'moving';
}
// vehicle.dart
base class Vehicle {
  String move() => 'moving';
}
// vehicle.dart
base class Vehicle {
  String move() => 'moving';
}

Dart example

// main.dart
import 'vehicle.dart';

final class Car extends Vehicle {}

void main() {
  print(Car().move()); // moving
}
// class Fake implements Vehicle {} // Invalid across libraries.
// main.dart
import 'vehicle.dart';

final class Car extends Vehicle {}

void main() {
  print(Car().move()); // moving
}
// class Fake implements Vehicle {} // Invalid across libraries.
// main.dart
import 'vehicle.dart';

final class Car extends Vehicle {}

void main() {
  print(Car().move()); // moving
}
// class Fake implements Vehicle {} // Invalid across libraries.

55. How can a sealed hierarchy model success and failure exhaustively?

A sealed root limits direct subtypes to its defining library, giving the analyzer a known set of cases for exhaustiveness checking. Model successful data and expected failure as separate variants, then use a switch expression without a catch-all. Adding a new variant forces relevant switches to be reconsidered instead of silently taking a default branch.

This is useful when failure is an expected domain outcome, such as a missing configuration entry. It does not replace exceptions for every unexpected defect. The final leaf classes below keep each variant closed, while object patterns expose its payload. All three classes belong to the same library.

Dart example

sealed class LookupResult {}
final class Found extends LookupResult {
  final String value;
  Found(this.value);
}
final class Missing extends LookupResult {
  final String key;
  Missing(this.key);
}

String describe(LookupResult result) => switch (result) {
  Found(value: final value) => 'Found $value',
  Missing(key: final key) => 'Missing $key',
};

void main() {
  print(describe(Found('Dart'))); // Found Dart
  print(describe(Missing('language'))); // Missing language
}
sealed class LookupResult {}
final class Found extends LookupResult {
  final String value;
  Found(this.value);
}
final class Missing extends LookupResult {
  final String key;
  Missing(this.key);
}

String describe(LookupResult result) => switch (result) {
  Found(value: final value) => 'Found $value',
  Missing(key: final key) => 'Missing $key',
};

void main() {
  print(describe(Found('Dart'))); // Found Dart
  print(describe(Missing('language'))); // Missing language
}
sealed class LookupResult {}
final class Found extends LookupResult {
  final String value;
  Found(this.value);
}
final class Missing extends LookupResult {
  final String key;
  Missing(this.key);
}

String describe(LookupResult result) => switch (result) {
  Found(value: final value) => 'Found $value',
  Missing(key: final key) => 'Missing $key',
};

void main() {
  print(describe(Found('Dart'))); // Found Dart
  print(describe(Missing('language'))); // Missing language
}

56. What defines a record's shape, type, and equality?

A record's shape consists of its positional-field count and its named-field names. Field types determine its static record type. Positional field labels in a type annotation are documentation only; named field names matter, but their written order does not.

Records provide structural equality and hashing based on corresponding fields. Their fields cannot be reassigned, but that does not make referenced mutable objects deeply immutable. For example, two records containing separately allocated lists generally compare unequal because lists use identity equality by default. Records work well for small, fixed data bundles; choose a class when the domain needs methods, validation, or an independently named runtime abstraction.

Dart example

void main() {
  ({String name, int count}) a = (name: 'queue', count: 2);
  final b = (count: 2, name: 'queue');
  print(a == b); // true
  print(a.name); // queue
  (int left, int right) pair = (3, 4);
  (int x, int y) renamed = pair;
  print(renamed.$2); // 4
  print(([1],) == ([1],)); // false: distinct lists
}
void main() {
  ({String name, int count}) a = (name: 'queue', count: 2);
  final b = (count: 2, name: 'queue');
  print(a == b); // true
  print(a.name); // queue
  (int left, int right) pair = (3, 4);
  (int x, int y) renamed = pair;
  print(renamed.$2); // 4
  print(([1],) == ([1],)); // false: distinct lists
}
void main() {
  ({String name, int count}) a = (name: 'queue', count: 2);
  final b = (count: 2, name: 'queue');
  print(a == b); // true
  print(a.name); // queue
  (int left, int right) pair = (3, 4);
  (int x, int y) renamed = pair;
  print(renamed.$2); // 4
  print(([1],) == ([1],)); // false: distinct lists
}

57. How do list, map, and object patterns validate and destructure data?

Patterns combine shape checks with extracting values. A list pattern can require an exact length or accept extra elements with a rest pattern. A map pattern requires its listed keys and matching values, but permits additional keys. An object pattern checks the object type and reads the named getters; it does not call a constructor or inspect private storage magically.

Use patterns in refutable contexts such as if-case when input may not match. A failed match then takes the alternative branch rather than forcing a cast. Object getters can still execute code or throw, and successful structural matching does not replace domain checks such as a positive identifier requirement.

Dart example

class User {
  final int id;
  User(this.id);
}

String describe(Object? value) => switch (value) {
  [int first, int second] => 'pair ${first + second}',
  {'id': int id} => 'map $id',
  User(id: int id) => 'user $id',
  _ => 'unsupported',
};

void main() {
  print(describe([2, 3])); // pair 5
  print(describe({'id': 7, 'extra': true})); // map 7
  print(describe(User(9))); // user 9
}
class User {
  final int id;
  User(this.id);
}

String describe(Object? value) => switch (value) {
  [int first, int second] => 'pair ${first + second}',
  {'id': int id} => 'map $id',
  User(id: int id) => 'user $id',
  _ => 'unsupported',
};

void main() {
  print(describe([2, 3])); // pair 5
  print(describe({'id': 7, 'extra': true})); // map 7
  print(describe(User(9))); // user 9
}
class User {
  final int id;
  User(this.id);
}

String describe(Object? value) => switch (value) {
  [int first, int second] => 'pair ${first + second}',
  {'id': int id} => 'map $id',
  User(id: int id) => 'user $id',
  _ => 'unsupported',
};

void main() {
  print(describe([2, 3])); // pair 5
  print(describe({'id': 7, 'extra': true})); // map 7
  print(describe(User(9))); // user 9
}

58. When should you use if-case patterns and when guards?

Use if-case when one shape or variant matters and a full switch would add unnecessary branches. A when guard adds a boolean condition after the structural pattern has matched, so it can refer to variables introduced by that pattern. If the guard is false, the case does not match.

Keep structural validation in the pattern and domain rules in the guard when that division improves readability. A guarded case does not cover every value of the matched type, so exhaustive switches may still need an unguarded alternative. The example accepts only a two-element integer list representing an increasing interval; other lengths, types, and descending ranges are rejected.

Dart example

String interval(Object? value) {
  if (value case [int start, int end] when start < end) {
    return '$start..$end';
  }
  return 'invalid';
}

void main() {
  print(interval([2, 8])); // 2..8
  print(interval([8, 2])); // invalid
  print(interval([2, 8, 9])); // invalid
}
String interval(Object? value) {
  if (value case [int start, int end] when start < end) {
    return '$start..$end';
  }
  return 'invalid';
}

void main() {
  print(interval([2, 8])); // 2..8
  print(interval([8, 2])); // invalid
  print(interval([2, 8, 9])); // invalid
}
String interval(Object? value) {
  if (value case [int start, int end] when start < end) {
    return '$start..$end';
  }
  return 'invalid';
}

void main() {
  print(interval([2, 8])); // 2..8
  print(interval([8, 2])); // invalid
  print(interval([2, 8, 9])); // invalid
}

59. How do a mixin's on constraint, super calls, and application order interact?

An on clause constrains the superclass that a mixin application requires, allowing the mixin to make valid super calls. It is not a constructor invocation and does not by itself supply the superclass implementation. When only ordinary members on this are needed, abstract members can express that requirement without a superclass constraint.

Mixins apply from left to right. Later mixins override earlier implementations, and their super calls proceed through the previously built superclass chain. Reordering mixins can therefore change behavior even when the code still compiles. The wrappers below deliberately expose the order: Second delegates to First, which delegates to Base.

Dart example

class Base {
  String describe() => 'base';
}
mixin First on Base {
  @override
  String describe() => 'first(${super.describe()})';
}
mixin Second on Base {
  @override
  String describe() => 'second(${super.describe()})';
}
class Combined extends Base with First, Second {}

void main() {
  print(Combined().describe()); // second(first(base))
}
class Base {
  String describe() => 'base';
}
mixin First on Base {
  @override
  String describe() => 'first(${super.describe()})';
}
mixin Second on Base {
  @override
  String describe() => 'second(${super.describe()})';
}
class Combined extends Base with First, Second {}

void main() {
  print(Combined().describe()); // second(first(base))
}
class Base {
  String describe() => 'base';
}
mixin First on Base {
  @override
  String describe() => 'first(${super.describe()})';
}
mixin Second on Base {
  @override
  String describe() => 'second(${super.describe()})';
}
class Combined extends Base with First, Second {}

void main() {
  print(Combined().describe()); // second(first(base))
}

60. How do typedefs, constructor tear-offs, and callable objects simplify APIs?

A typedef gives a function signature a readable name without introducing a new nominal function type. Constructor tear-offs such as Item.new provide a constructor as a function value, avoiding an unnecessary forwarding closure when its signature already matches.

A class with a call method can be invoked like a function, while also carrying configuration or state. An explicit .call tear-off is useful when an API expects a function and the distinction should be obvious. Keep the signature precise rather than using Function, which loses parameter and return-type checking. The example combines constructor mapping with a configured predicate that filters the resulting objects.

Dart example

class Item {
  final String name;
  Item(this.name);
}
typedef ItemTest = bool Function(Item item);
class MinimumLength {
  final int minimum;
  MinimumLength(this.minimum);
  bool call(Item item) => item.name.length >= minimum;
}

void main() {
  final items = ['a', 'dart'].map(Item.new);
  final rule = MinimumLength(3);
  ItemTest accepted = rule.call;
  print(items.where(accepted).single.name); // dart
  print(rule(Item('api'))); // true
}
class Item {
  final String name;
  Item(this.name);
}
typedef ItemTest = bool Function(Item item);
class MinimumLength {
  final int minimum;
  MinimumLength(this.minimum);
  bool call(Item item) => item.name.length >= minimum;
}

void main() {
  final items = ['a', 'dart'].map(Item.new);
  final rule = MinimumLength(3);
  ItemTest accepted = rule.call;
  print(items.where(accepted).single.name); // dart
  print(rule(Item('api'))); // true
}
class Item {
  final String name;
  Item(this.name);
}
typedef ItemTest = bool Function(Item item);
class MinimumLength {
  final int minimum;
  MinimumLength(this.minimum);
  bool call(Item item) => item.name.length >= minimum;
}

void main() {
  final items = ['a', 'dart'].map(Item.new);
  final rule = MinimumLength(3);
  ItemTest accepted = rule.call;
  print(items.where(accepted).single.name); // dart
  print(rule(Item('api'))); // true
}

61. How do you validate decoded JSON before constructing a typed model?

jsonDecode produces dynamically typed JSON values, not instances of an application model. Treat its result as untrusted data: check the outer structure, required keys, value types, and domain rules before constructing a typed object. A cast alone can defer failures and often produces poor diagnostics.

Map patterns express required keys and types compactly, while guards enforce constraints such as positive identifiers. They allow extra keys, so reject unknown keys separately if the schema requires that. Decide deliberately whether a numeric field accepts any num or only int; do not silently truncate fractional values. Here, syntax errors and invalid model data both surface as FormatException failures.

Dart example

import 'dart:convert';

class User {
  final int id;
  final String name;
  User(this.id, this.name);

  factory User.fromJson(Object? value) {
    if (value case {'id': int id, 'name': String name}
        when id > 0 && name.trim().isNotEmpty) {
      return User(id, name.trim());
    }
    throw FormatException('Expected a positive id and non-empty name');
  }
}

void main() {
  final user = User.fromJson(jsonDecode('{"id":7,"name":" Ada "}'));
  print('${user.id}: ${user.name}'); // 7: Ada
}
import 'dart:convert';

class User {
  final int id;
  final String name;
  User(this.id, this.name);

  factory User.fromJson(Object? value) {
    if (value case {'id': int id, 'name': String name}
        when id > 0 && name.trim().isNotEmpty) {
      return User(id, name.trim());
    }
    throw FormatException('Expected a positive id and non-empty name');
  }
}

void main() {
  final user = User.fromJson(jsonDecode('{"id":7,"name":" Ada "}'));
  print('${user.id}: ${user.name}'); // 7: Ada
}
import 'dart:convert';

class User {
  final int id;
  final String name;
  User(this.id, this.name);

  factory User.fromJson(Object? value) {
    if (value case {'id': int id, 'name': String name}
        when id > 0 && name.trim().isNotEmpty) {
      return User(id, name.trim());
    }
    throw FormatException('Expected a positive id and non-empty name');
  }
}

void main() {
  final user = User.fromJson(jsonDecode('{"id":7,"name":" Ada "}'));
  print('${user.id}: ${user.name}'); // 7: Ada
}

62. How do you serialize a Dart model without assuming every object is JSON-compatible?

JSON encoding supports null, booleans, strings, numbers, lists, and maps with string keys, subject to JSON's restrictions such as finite numeric values. Arbitrary Dart objects, dates, sets, and cyclic object graphs are not automatically valid JSON structures.

Define a toJson method that returns a compatible representation, or provide toEncodable to the encoder. The default conversion attempts an object's toJson method, but every value it returns must still be encodable. Choose an explicit wire format for dates and identifiers, and keep it symmetric with deserialization. The example converts a timestamp to a UTC ISO-8601 string rather than relying on an object's debugging toString representation.

Dart example

import 'dart:convert';

class Invoice {
  final int cents;
  final DateTime issuedAt;
  Invoice(this.cents, this.issuedAt);

  Map<String, Object?> toJson() => {
    'cents': cents,
    'issuedAt': issuedAt.toUtc().toIso8601String(),
  };
}

void main() {
  final invoice = Invoice(1250, DateTime.utc(2026, 1, 1));
  print(jsonEncode(invoice));
  // {"cents":1250,"issuedAt":"2026-01-01T00:00:00.000Z"}
}
import 'dart:convert';

class Invoice {
  final int cents;
  final DateTime issuedAt;
  Invoice(this.cents, this.issuedAt);

  Map<String, Object?> toJson() => {
    'cents': cents,
    'issuedAt': issuedAt.toUtc().toIso8601String(),
  };
}

void main() {
  final invoice = Invoice(1250, DateTime.utc(2026, 1, 1));
  print(jsonEncode(invoice));
  // {"cents":1250,"issuedAt":"2026-01-01T00:00:00.000Z"}
}
import 'dart:convert';

class Invoice {
  final int cents;
  final DateTime issuedAt;
  Invoice(this.cents, this.issuedAt);

  Map<String, Object?> toJson() => {
    'cents': cents,
    'issuedAt': issuedAt.toUtc().toIso8601String(),
  };
}

void main() {
  final invoice = Invoice(1250, DateTime.utc(2026, 1, 1));
  print(jsonEncode(invoice));
  // {"cents":1250,"issuedAt":"2026-01-01T00:00:00.000Z"}
}

63. How do sync*, async*, yield, and yield* differ?

A sync* function returns an Iterable whose body advances as values are requested. Each iteration starts a fresh traversal. An async* function returns a single-subscription Stream; its body starts when listened to and can await asynchronous operations between events.

yield produces one value. yield* delegates to an iterable in a synchronous generator or a stream in an asynchronous generator, avoiding a manual forwarding loop. Returning ends the generator rather than producing a final value. In an async* generator, use try/finally for owned resources and await subscription cancellation. Abandoning a sync* iterator does not guarantee its finally executes because iterators have no close operation. Cancellation is not an immediate interrupt for arbitrary synchronous work.

Dart example

Iterable<int> sequence() sync* {
  yield 1;
  yield* [2, 3];
}

Stream<int> events() async* {
  yield 0;
  await Future<void>.delayed(Duration.zero);
  yield* Stream<int>.fromIterable(sequence());
}

Future<void> main() async {
  print(sequence().toList()); // [1, 2, 3]
  print(await events().toList()); // [0, 1, 2, 3]
}
Iterable<int> sequence() sync* {
  yield 1;
  yield* [2, 3];
}

Stream<int> events() async* {
  yield 0;
  await Future<void>.delayed(Duration.zero);
  yield* Stream<int>.fromIterable(sequence());
}

Future<void> main() async {
  print(sequence().toList()); // [1, 2, 3]
  print(await events().toList()); // [0, 1, 2, 3]
}
Iterable<int> sequence() sync* {
  yield 1;
  yield* [2, 3];
}

Stream<int> events() async* {
  yield 0;
  await Future<void>.delayed(Duration.zero);
  yield* Stream<int>.fromIterable(sequence());
}

Future<void> main() async {
  print(sequence().toList()); // [1, 2, 3]
  print(await events().toList()); // [0, 1, 2, 3]
}

64. What order do synchronous code, microtasks, and event-queue tasks run in?

Within an isolate, current synchronous code finishes before queued callbacks run. The microtask queue is drained before the next event-queue task, so microtasks scheduled during the current turn run before a newly scheduled timer or ordinary Future constructor callback. Repeatedly adding microtasks can starve event processing.

Do not infer scheduling from the word Future alone: different constructors and completion states have different behavior, and an async function starts synchronously until suspension. Neither a microtask nor an ordinary future creates a worker isolate or makes CPU-heavy synchronous code parallel. The example deliberately uses scheduleMicrotask and the ordinary Future constructor to make the queue distinction explicit.

Dart example

import 'dart:async';

void main() {
  print('sync start');
  scheduleMicrotask(() => print('microtask'));
  Future<void>(() => print('event'));
  print('sync end');
}
// Expected order:
// sync start
// sync end
// microtask
// event
import 'dart:async';

void main() {
  print('sync start');
  scheduleMicrotask(() => print('microtask'));
  Future<void>(() => print('event'));
  print('sync end');
}
// Expected order:
// sync start
// sync end
// microtask
// event
import 'dart:async';

void main() {
  print('sync start');
  scheduleMicrotask(() => print('microtask'));
  Future<void>(() => print('event'));
  print('sync end');
}
// Expected order:
// sync start
// sync end
// microtask
// event

65. How do you start independent asynchronous operations concurrently and preserve result order?

Call independent asynchronous operations before awaiting their combined result. Awaiting the first operation before starting the second introduces an unnecessary dependency and increases total latency. Future.wait collects results in input order, even when the operations finish in a different order.

This is concurrency, not necessarily CPU parallelism: both callbacks still run in their isolate unless the underlying work is delegated elsewhere. Attach combined error handling promptly so a rapidly failing operation is not left unobserved. The example starts both delayed operations together and reports the slower first argument first. For large inputs, add a concurrency limit rather than starting an unbounded number of network or file operations.

Dart example

Future<String> load(String name, int milliseconds) async {
  await Future<void>.delayed(Duration(milliseconds: milliseconds));
  return name;
}

Future<void> main() async {
  final first = load('first', 20);
  final second = load('second', 1);
  final results = await Future.wait<String>([first, second]);
  print(results); // [first, second]
}
Future<String> load(String name, int milliseconds) async {
  await Future<void>.delayed(Duration(milliseconds: milliseconds));
  return name;
}

Future<void> main() async {
  final first = load('first', 20);
  final second = load('second', 1);
  final results = await Future.wait<String>([first, second]);
  print(results); // [first, second]
}
Future<String> load(String name, int milliseconds) async {
  await Future<void>.delayed(Duration(milliseconds: milliseconds));
  return name;
}

Future<void> main() async {
  final first = load('first', 20);
  final second = load('second', 1);
  final results = await Future.wait<String>([first, second]);
  print(results); // [first, second]
}

66. What do Future.wait's eagerError and cleanUp options actually guarantee?

With eagerError: false, Future.wait waits for every input before reporting the first error. With true, it reports the first error sooner, but does not cancel remaining operations. Additional input errors are not returned as an aggregate.

After a failure, cleanUp receives each non-null successful result, including results that arrive later. It is not called when every operation succeeds. The callback must not throw: a thrown cleanup error becomes an uncaught asynchronous error. Its signature is synchronous, so Future.wait does not await asynchronous disposal returned by an async callback. Resources requiring awaited cleanup need an explicit ownership design. This example uses deliberately synchronous cleanup.

Dart example

class Resource {
  final String name;
  Resource(this.name);
  void close() => print('closed $name');
}

Future<void> main() async {
  try {
    await Future.wait<Resource>([
      Future<Resource>.value(Resource('A')),
      Future<Resource>.error(StateError('B failed')),
    ], cleanUp: (resource) => resource.close());
  } on StateError {
    print('failed');
  }
}
// Expected output:
// closed A
// failed
class Resource {
  final String name;
  Resource(this.name);
  void close() => print('closed $name');
}

Future<void> main() async {
  try {
    await Future.wait<Resource>([
      Future<Resource>.value(Resource('A')),
      Future<Resource>.error(StateError('B failed')),
    ], cleanUp: (resource) => resource.close());
  } on StateError {
    print('failed');
  }
}
// Expected output:
// closed A
// failed
class Resource {
  final String name;
  Resource(this.name);
  void close() => print('closed $name');
}

Future<void> main() async {
  try {
    await Future.wait<Resource>([
      Future<Resource>.value(Resource('A')),
      Future<Resource>.error(StateError('B failed')),
    ], cleanUp: (resource) => resource.close());
  } on StateError {
    print('failed');
  }
}
// Expected output:
// closed A
// failed

67. When does try/catch require return await to intercept a Future failure?

A local try/catch catches a synchronous throw from an invoked function, but it cannot catch a later failure merely because a future was returned inside the try. In an async function, return await operation() keeps that future's completion within the protected region, allowing local recovery or translation of the error.

Without the await, the returned future still forwards failure to the caller, but the local catch does not intercept its asynchronous completion. Use rethrow when propagating the same caught exception and stack trace. Awaiting is also important when finally must run after the asynchronous operation finishes, rather than immediately after obtaining its future.

Dart example

Future<int> readCount() async {
  throw FormatException('Invalid count');
}

Future<int> readOrDefault() async {
  try {
    return await readCount();
  } on FormatException {
    return 0;
  }
}

Future<void> main() async {
  print(await readOrDefault()); // 0
}
Future<int> readCount() async {
  throw FormatException('Invalid count');
}

Future<int> readOrDefault() async {
  try {
    return await readCount();
  } on FormatException {
    return 0;
  }
}

Future<void> main() async {
  print(await readOrDefault()); // 0
}
Future<int> readCount() async {
  throw FormatException('Invalid count');
}

Future<int> readOrDefault() async {
  try {
    return await readCount();
  } on FormatException {
    return 0;
  }
}

Future<void> main() async {
  print(await readOrDefault()); // 0
}

68. Does Future.timeout cancel the underlying operation?

Future.timeout creates a new future that stops waiting after the deadline; it does not cancel the source operation. Without onTimeout, that wrapper fails with TimeoutException. A supplied callback can return a fallback value or future, or throw. Once timeout wins, the source's eventual result does not replace the wrapper's result.

The underlying network request, file operation, or other side effect may still finish. Actual cancellation requires support from the operation itself, plus clear cleanup ownership. Retrying a timed-out write can duplicate its effect, so design idempotency separately. The controlled example proves the distinction without depending on an uncertain network response time.

Dart example

import 'dart:async';

Future<void> main() async {
  final source = Completer<String>();
  final result = await source.future.timeout(
    Duration.zero, onTimeout: () => 'fallback');
  print(result); // fallback
  source.complete('completed later');
  print(await source.future); // completed later
}
import 'dart:async';

Future<void> main() async {
  final source = Completer<String>();
  final result = await source.future.timeout(
    Duration.zero, onTimeout: () => 'fallback');
  print(result); // fallback
  source.complete('completed later');
  print(await source.future); // completed later
}
import 'dart:async';

Future<void> main() async {
  final source = Completer<String>();
  final result = await source.future.timeout(
    Duration.zero, onTimeout: () => 'fallback');
  print(result); // fallback
  source.complete('completed later');
  print(await source.future); // completed later
}

69. How do single-subscription and broadcast streams differ?

A single-subscription stream permits one listener over its lifetime, even after that subscription is canceled. It suits ordered data that should not be missed, such as a file read. A broadcast stream supports multiple listeners, each with its own subscription and pause state.

Broadcast does not mean replay: ordinary broadcast controllers discard events when no listener exists, and a new listener does not receive earlier events. Pausing one listener need not pause the producer; events may accumulate for that subscription. Choose semantics based on ownership and delivery requirements rather than converting every stream to broadcast. The example uses an asynchronous broadcast controller and subscribes both consumers before sending an event.

Dart example

import 'dart:async';

Future<void> main() async {
  final controller = StreamController<int>.broadcast();
  controller.add(0); // No listeners: discarded.
  final first = <int>[];
  final second = <int>

import 'dart:async';

Future<void> main() async {
  final controller = StreamController<int>.broadcast();
  controller.add(0); // No listeners: discarded.
  final first = <int>[];
  final second = <int>

import 'dart:async';

Future<void> main() async {
  final controller = StreamController<int>.broadcast();
  controller.add(0); // No listeners: discarded.
  final first = <int>[];
  final second = <int>

70. How do map and asyncMap differ when processing a stream?

map applies a synchronous transformation to each data event. If its callback returns a future, the result is a stream of futures; map does not automatically await or flatten them. asyncMap accepts a value or future and emits the resolved value instead.

When an asyncMap callback returns a future, processing waits for that future before converting the next event, preserving ordered sequential conversion rather than introducing parallel workers. Conversion failures become error events. For higher throughput, use an explicitly bounded concurrent design and decide whether output order must be preserved. Both methods transform data events without making a single-subscription source reusable.

Dart example

Future<int> doubleLater(int value) async => value * 2;

Future<void> main() async {
  final futureEvents = Stream<int>.fromIterable([1, 2])
      .map(doubleLater); // Stream<Future<int>>
  final pending = await futureEvents.toList();
  print(await Future.wait(pending)); // [2, 4]

  final values = Stream<int>.fromIterable([1, 2])
      .asyncMap(doubleLater); // Stream<int>
  print(await values.toList()); // [2, 4]
}
Future<int> doubleLater(int value) async => value * 2;

Future<void> main() async {
  final futureEvents = Stream<int>.fromIterable([1, 2])
      .map(doubleLater); // Stream<Future<int>>
  final pending = await futureEvents.toList();
  print(await Future.wait(pending)); // [2, 4]

  final values = Stream<int>.fromIterable([1, 2])
      .asyncMap(doubleLater); // Stream<int>
  print(await values.toList()); // [2, 4]
}
Future<int> doubleLater(int value) async => value * 2;

Future<void> main() async {
  final futureEvents = Stream<int>.fromIterable([1, 2])
      .map(doubleLater); // Stream<Future<int>>
  final pending = await futureEvents.toList();
  print(await Future.wait(pending)); // [2, 4]

  final values = Stream<int>.fromIterable([1, 2])
      .asyncMap(doubleLater); // Stream<int>
  print(await values.toList()); // [2, 4]
}

71. Who owns a StreamSubscription, and how should it be paused and canceled?

The component calling listen normally owns the returned subscription and must decide when to stop listening. Keep that handle, register error handling, and await cancel() when subsequent work depends on source cleanup. Cancellation stops further delivery; its future represents completion of any asynchronous cleanup.

pause temporarily suspends delivery, and each pause must be balanced by a resume or a supplied resume signal. The producer may pause or the subscription may buffer, especially for broadcast streams, so pausing is not a universal memory bound. Cancel and resubscribe only when dropping intervening events is acceptable and the stream supports another listener. The finite example resumes before waiting for completion.

Dart example

import 'dart:async';

Future<void> main() async {
  final done = Completer<void>();
  final subscription = Stream<int>.fromIterable([1, 2]).listen(
    print,
    onError: (Object error, StackTrace stack) =>
        done.completeError(error, stack),
    onDone: () => done.complete(),
    cancelOnError: true,
  );
  try {
    subscription.pause();
    subscription.resume();
    await done.future;
  } finally {
    await subscription.cancel();
  }
}
// Expected output: 1, then 2 on separate lines.
import 'dart:async';

Future<void> main() async {
  final done = Completer<void>();
  final subscription = Stream<int>.fromIterable([1, 2]).listen(
    print,
    onError: (Object error, StackTrace stack) =>
        done.completeError(error, stack),
    onDone: () => done.complete(),
    cancelOnError: true,
  );
  try {
    subscription.pause();
    subscription.resume();
    await done.future;
  } finally {
    await subscription.cancel();
  }
}
// Expected output: 1, then 2 on separate lines.
import 'dart:async';

Future<void> main() async {
  final done = Completer<void>();
  final subscription = Stream<int>.fromIterable([1, 2]).listen(
    print,
    onError: (Object error, StackTrace stack) =>
        done.completeError(error, stack),
    onDone: () => done.complete(),
    cancelOnError: true,
  );
  try {
    subscription.pause();
    subscription.resume();
    await done.future;
  } finally {
    await subscription.cancel();
  }
}
// Expected output: 1, then 2 on separate lines.

72. How do you create and close a StreamController without losing lifecycle control?

Keep the controller private to the producer and expose only its stream to consumers. The owner should decide when production starts, how errors are emitted, and when the controller closes. Use onListen, onPause, onResume, and onCancel when an external producer needs corresponding lifecycle signals.

The default controller delivers asynchronously; use sync: true only when its stricter delivery contract is understood. Closing prevents further events, but its returned future can wait for listeners to finish. A never-listened single-subscription stream or a permanently paused listener can leave that future pending. Subscribe before awaiting close, stop external production first, and do not mistake controller closure for disposing unrelated timers or sockets.

Dart example

import 'dart:async';

class CounterFeed {
  final _controller = StreamController<int>();
  Stream<int> get stream => _controller.stream;
  void add(int value) => _controller.add(value);
  Future<void> close() async {
    await _controller.close();
  }
}

Future<void> main() async {
  final feed = CounterFeed();
  final values = feed.stream.toList(); // Subscribes now.
  feed.add(1);
  feed.add(2);
  await feed.close();
  print(await values); // [1, 2]
}
import 'dart:async';

class CounterFeed {
  final _controller = StreamController<int>();
  Stream<int> get stream => _controller.stream;
  void add(int value) => _controller.add(value);
  Future<void> close() async {
    await _controller.close();
  }
}

Future<void> main() async {
  final feed = CounterFeed();
  final values = feed.stream.toList(); // Subscribes now.
  feed.add(1);
  feed.add(2);
  await feed.close();
  print(await values); // [1, 2]
}
import 'dart:async';

class CounterFeed {
  final _controller = StreamController<int>();
  Stream<int> get stream => _controller.stream;
  void add(int value) => _controller.add(value);
  Future<void> close() async {
    await _controller.close();
  }
}

Future<void> main() async {
  final feed = CounterFeed();
  final values = feed.stream.toList(); // Subscribes now.
  feed.add(1);
  feed.add(2);
  await feed.close();
  print(await values); // [1, 2]
}

73. How do you read a large text file incrementally on native Dart?

On native Dart, File.openRead produces byte chunks instead of loading the entire file into memory. Pipe those chunks through utf8.decoder and LineSplitter so multibyte characters and lines split across chunk boundaries are handled correctly. Decoding each byte chunk independently can break a character divided between chunks.

Consume the resulting stream with await for and process each line as it arrives rather than calling toList. A very long individual line can still require substantial memory. File and decoding failures propagate through the stream; handle them at the application's boundary. This command-line example requires a file path and uses dart:io, so it is not browser Dart.

Dart example

import 'dart:convert';
import 'dart:io';

Future<void> main(List<String> args) async {
  if (args.length != 1) {
    throw ArgumentError('Usage: dart run count_lines.dart <path>');
  }
  var count = 0;
  final lines = File(args.single).openRead()
      .transform(utf8.decoder)
      .transform(const LineSplitter());
  await for (final line in lines) {
    if (line.trim().isNotEmpty) count++;
  }
  print(count);
}
// A file with alpha, a blank line, and beta prints 2.
import 'dart:convert';
import 'dart:io';

Future<void> main(List<String> args) async {
  if (args.length != 1) {
    throw ArgumentError('Usage: dart run count_lines.dart <path>');
  }
  var count = 0;
  final lines = File(args.single).openRead()
      .transform(utf8.decoder)
      .transform(const LineSplitter());
  await for (final line in lines) {
    if (line.trim().isNotEmpty) count++;
  }
  print(count);
}
// A file with alpha, a blank line, and beta prints 2.
import 'dart:convert';
import 'dart:io';

Future<void> main(List<String> args) async {
  if (args.length != 1) {
    throw ArgumentError('Usage: dart run count_lines.dart <path>');
  }
  var count = 0;
  final lines = File(args.single).openRead()
      .transform(utf8.decoder)
      .transform(const LineSplitter());
  await for (final line in lines) {
    if (line.trim().isNotEmpty) count++;
  }
  print(count);
}
// A file with alpha, a blank line, and beta prints 2.

74. How do you close native file handles reliably when an operation fails?

Acquire a native file handle before entering the protected body, then close it in an awaited finally. If opening fails, no handle was acquired and there is nothing to close. Once opening succeeds, cleanup must happen whether reading, writing, or application logic throws.

A cleanup failure can replace an earlier exception, so applications that need both failures should capture and report them deliberately. Do not return from finally, because that can suppress the operation's result or error. Prefer higher-level file methods when they already provide the needed ownership behavior; explicit handles are appropriate for operations such as random-access reads. This example closes its read-only handle even if readByte fails.

Dart example

import 'dart:io';

Future<int> firstByte(String path) async {
  final handle = await File(path).open(mode: FileMode.read);
  try {
    return await handle.readByte();
  } finally {
    await handle.close();
  }
}

Future<void> main(List<String> args) async {
  if (args.length != 1) throw ArgumentError('Pass a file path');
  print(await firstByte(args.single));
}
// A file starting with ASCII A prints 65; an empty file prints -1.
import 'dart:io';

Future<int> firstByte(String path) async {
  final handle = await File(path).open(mode: FileMode.read);
  try {
    return await handle.readByte();
  } finally {
    await handle.close();
  }
}

Future<void> main(List<String> args) async {
  if (args.length != 1) throw ArgumentError('Pass a file path');
  print(await firstByte(args.single));
}
// A file starting with ASCII A prints 65; an empty file prints -1.
import 'dart:io';

Future<int> firstByte(String path) async {
  final handle = await File(path).open(mode: FileMode.read);
  try {
    return await handle.readByte();
  } finally {
    await handle.close();
  }
}

Future<void> main(List<String> args) async {
  if (args.length != 1) throw ArgumentError('Pass a file path');
  print(await firstByte(args.single));
}
// A file starting with ASCII A prints 65; an empty file prints -1.

75. How do you construct request URIs, handle HTTP status codes, and close an owned client?

Build URIs with their structured constructors so query values are encoded rather than concatenated into a URL. An HTTP response with a failure status is still a received response, not automatically a thrown network exception, so check the status before interpreting its body.

Reuse a client across related requests and close it when its owner finishes. A helper receiving an injected client should not close a client owned by its caller. Browser and native transports have different constraints, including browser CORS enforcement. This example uses package:http; add it as a dependency first. It accepts only HTTPS URLs, checks for a successful status, and closes its locally owned client in finally.

Dart example

import 'package:http/http.dart' as http;

Future<void> main(List<String> args) async {
  if (args.length != 1) throw ArgumentError('Pass an HTTPS URL');
  final base = Uri.parse(args.single);
  if (base.scheme != 'https' || base.host.isEmpty) {
    throw ArgumentError('An absolute HTTPS URL is required');
  }
  final uri = base.replace(queryParameters: {
    ...base.queryParameters, 'q': 'dart streams',
  });
  final client = http.Client();
  try {
    final response = await client.get(uri);
    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw StateError('HTTP ${response.statusCode}');
    }
    print(response.body); // Output depends on the server response.
  } finally {
    client.close();
  }
}
import 'package:http/http.dart' as http;

Future<void> main(List<String> args) async {
  if (args.length != 1) throw ArgumentError('Pass an HTTPS URL');
  final base = Uri.parse(args.single);
  if (base.scheme != 'https' || base.host.isEmpty) {
    throw ArgumentError('An absolute HTTPS URL is required');
  }
  final uri = base.replace(queryParameters: {
    ...base.queryParameters, 'q': 'dart streams',
  });
  final client = http.Client();
  try {
    final response = await client.get(uri);
    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw StateError('HTTP ${response.statusCode}');
    }
    print(response.body); // Output depends on the server response.
  } finally {
    client.close();
  }
}
import 'package:http/http.dart' as http;

Future<void> main(List<String> args) async {
  if (args.length != 1) throw ArgumentError('Pass an HTTPS URL');
  final base = Uri.parse(args.single);
  if (base.scheme != 'https' || base.host.isEmpty) {
    throw ArgumentError('An absolute HTTPS URL is required');
  }
  final uri = base.replace(queryParameters: {
    ...base.queryParameters, 'q': 'dart streams',
  });
  final client = http.Client();
  try {
    final response = await client.get(uri);
    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw StateError('HTTP ${response.statusCode}');
    }
    print(response.body); // Output depends on the server response.
  } finally {
    client.close();
  }
}

76. How do you write tests for Futures, errors, and streams?

Return or await asynchronous work from a test so the test runner observes its completion and failures. Use expectLater with completion for a future's successful value, a throwing matcher for a future error, and stream matchers for event sequences. Awaiting these expectations makes their lifetime explicit.

For synchronous exceptions, pass a closure to expect rather than calling the throwing function before the matcher is installed. Prefer controlled futures and streams over real-time delays or external services, and close resources in teardown when tests own them. Save this example under test/async_test.dart, add test as a dev dependency, and run it with dart test.

Dart example

import 'package:test/test.dart';

Future<int> answer() async => 42;
Future<int> invalid() async => throw FormatException('bad input');
Stream<int> events() async* {
  yield 1;
  throw StateError('stopped');
}

void main() {
  test('future value', () async {
    await expectLater(answer(), completion(42));
  });
  test('future error', () async {
    await expectLater(invalid(), throwsA(isA<FormatException>()));
  });
  test('stream data, error, and completion', () async {
    await expectLater(events(), emitsInOrder([
      1, emitsError(isA<StateError>()), emitsDone,
    ]));
  });
}
// Expected result: all three tests pass.
import 'package:test/test.dart';

Future<int> answer() async => 42;
Future<int> invalid() async => throw FormatException('bad input');
Stream<int> events() async* {
  yield 1;
  throw StateError('stopped');
}

void main() {
  test('future value', () async {
    await expectLater(answer(), completion(42));
  });
  test('future error', () async {
    await expectLater(invalid(), throwsA(isA<FormatException>()));
  });
  test('stream data, error, and completion', () async {
    await expectLater(events(), emitsInOrder([
      1, emitsError(isA<StateError>()), emitsDone,
    ]));
  });
}
// Expected result: all three tests pass.
import 'package:test/test.dart';

Future<int> answer() async => 42;
Future<int> invalid() async => throw FormatException('bad input');
Stream<int> events() async* {
  yield 1;
  throw StateError('stopped');
}

void main() {
  test('future value', () async {
    await expectLater(answer(), completion(42));
  });
  test('future error', () async {
    await expectLater(invalid(), throwsA(isA<FormatException>()));
  });
  test('stream data, error, and completion', () async {
    await expectLater(events(), emitsInOrder([
      1, emitsError(isA<StateError>()), emitsDone,
    ]));
  });
}
// Expected result: all three tests pass.

77. How do dependencies, dev_dependencies, SDK constraints, and lockfiles fit together?

Put packages used by shipped library or application code in dependencies. Put testing, code generation, and development-only tooling in dev_dependencies; a package consumer does not inherit that package's dev dependencies. SDK constraints declare compatible Dart versions, and the lower SDK bound also determines the package's default language version.

The pubspec describes allowed dependency ranges, while pubspec.lock records the concrete resolution, including transitive packages. Applications should commit their lockfile for reproducibility; reusable packages generally should not commit it and must test their supported ranges. dart pub get prefers an existing compatible lockfile, whereas dart pub upgrade deliberately seeks newer allowed versions. The versions below illustrate bounds, not a promise of the newest package releases.

YAML example

name: interview_examples
environment:
  sdk: '>=3.13.0 <4.0.0'
dependencies:
  http: ^1.6.0
dev_dependencies:
  test

name: interview_examples
environment:
  sdk: '>=3.13.0 <4.0.0'
dependencies:
  http: ^1.6.0
dev_dependencies:
  test

name: interview_examples
environment:
  sdk: '>=3.13.0 <4.0.0'
dependencies:
  http: ^1.6.0
dev_dependencies:
  test

78. How do analyzer settings and lints enforce stricter typing?

The analyzer already enforces Dart's sound type rules, while stricter language settings catch additional reliance on permissive inference or dynamic values. strict-casts rejects implicit downcasts from dynamic, strict-inference flags inference that lacks sufficient information, and strict-raw-types flags missing generic type arguments.

Lints add maintainability rules on top of type checking; they do not turn every runtime validation problem into a compile-time proof. Keep configuration in analysis_options.yaml, run dart analyze in CI, and use narrow, explained suppressions instead of disabling entire rule families. The configuration below also flags accidentally discarded futures. An explicit cast may satisfy analysis while still failing at runtime, so validate untrusted inputs structurally.

YAML example

analyzer:
  language:
    strict-casts: true
    strict-inference: true
    strict-raw-types: true
linter:
  rules

analyzer:
  language:
    strict-casts: true
    strict-inference: true
    strict-raw-types: true
linter:
  rules

analyzer:
  language:
    strict-casts: true
    strict-inference: true
    strict-raw-types: true
linter:
  rules

79. How would you remove duplicates while preserving first-seen order?

Track values already seen in an insertion-ordered set and append only values whose first insertion succeeds. Dart's default set literal uses insertion-order iteration, so values.toSet().toList() is a concise option when equality of the whole value defines duplication. An explicit loop also supports custom identity keys and other filtering rules.

For domain objects, decide whether duplicates mean equal objects, equal IDs, or normalized text. Equality and hash codes must be consistent, and key fields should not change while stored. The generic function below uses ordinary value equality, preserves the first representative, accepts empty input, and creates a new output list without modifying the source.

Dart example

List<T> uniqueInOrder<T>(Iterable<T> values) {
  final seen = <T>{};
  return [for (final value in values) if (seen.add(value)) value];
}

void main() {
  final source = ['b', 'a', 'b', 'c', 'a'];
  print(uniqueInOrder(source)); // [b, a, c]
  print(uniqueInOrder<int>

List<T> uniqueInOrder<T>(Iterable<T> values) {
  final seen = <T>{};
  return [for (final value in values) if (seen.add(value)) value];
}

void main() {
  final source = ['b', 'a', 'b', 'c', 'a'];
  print(uniqueInOrder(source)); // [b, a, c]
  print(uniqueInOrder<int>

List<T> uniqueInOrder<T>(Iterable<T> values) {
  final seen = <T>{};
  return [for (final value in values) if (seen.add(value)) value];
}

void main() {
  final source = ['b', 'a', 'b', 'c', 'a'];
  print(uniqueInOrder(source)); // [b, a, c]
  print(uniqueInOrder<int>

80. How would you group and total records by a key without mutating the input?

Accumulate into a new map keyed by the grouping field, updating each total without sorting or rewriting the input. Map.update handles existing keys and an ifAbsent callback establishes the first total. For ordinary hash-map keys, the operation is expected linear in row count and uses space proportional to the number of groups.

Records make the input shape explicit, while integer minor units avoid binary floating-point rounding in this small money example. Choose a numeric representation appropriate to the target platform and expected range. Empty input naturally returns an empty map, negative values can represent refunds, and the default map preserves the order in which groups first appear.

Dart example

typedef Sale = ({String category, int cents});

Map<String, int> totalsByCategory(Iterable<Sale> rows) {
  final totals = <String, int>{};
  for (final row in rows) {
    totals.update(row.category, (total) => total + row.cents,
        ifAbsent: () => row.cents);
  }
  return totals;
}

void main() {
  const rows = <Sale>[
    (category: 'books', cents: 1200),
    (category: 'tools', cents: 500),
    (category: 'books', cents: -200),
  ];
  print(totalsByCategory(rows)); // {books

typedef Sale = ({String category, int cents});

Map<String, int> totalsByCategory(Iterable<Sale> rows) {
  final totals = <String, int>{};
  for (final row in rows) {
    totals.update(row.category, (total) => total + row.cents,
        ifAbsent: () => row.cents);
  }
  return totals;
}

void main() {
  const rows = <Sale>[
    (category: 'books', cents: 1200),
    (category: 'tools', cents: 500),
    (category: 'books', cents: -200),
  ];
  print(totalsByCategory(rows)); // {books

typedef Sale = ({String category, int cents});

Map<String, int> totalsByCategory(Iterable<Sale> rows) {
  final totals = <String, int>{};
  for (final row in rows) {
    totals.update(row.category, (total) => total + row.cents,
        ifAbsent: () => row.cents);
  }
  return totals;
}

void main() {
  const rows = <Sale>[
    (category: 'books', cents: 1200),
    (category: 'tools', cents: 500),
    (category: 'books', cents: -200),
  ];
  print(totalsByCategory(rows)); // {books

Dart Interview Questions and Answers for Experienced

The experienced answers connect design decisions to observable behavior and testable assumptions. Platform-sensitive discussions identify the relevant native, JavaScript, or WebAssembly target rather than assuming that one successful execution proves portability.

81. How do Object, Object?, dynamic, void, and Never differ in API design?

Object accepts any non-null Dart object; Object? also accepts null and is the safer starting point for unknown input. Both require narrowing before type-specific operations. dynamic permits operations without those static checks, moving possible failures to runtime; it does not make invalid operations succeed.

void declares that a result is not intended to be used. It is not a promise that the runtime result is null. Never has no values and describes code that cannot complete normally, such as a throwing helper. That distinction lets flow analysis recognize unreachable paths. Public APIs should expose meaningful types rather than use dynamic merely to avoid designing a contract. The example accepts unknown input but returns only validated text.

Dart example

Never invalidText() => throw const FormatException('Expected text');

String requireText(Object? value) {
  if (value is String) return value;
  invalidText();
}

void main() {
  print(requireText('ready')); // ready
}
Never invalidText() => throw const FormatException('Expected text');

String requireText(Object? value) {
  if (value is String) return value;
  invalidText();
}

void main() {
  print(requireText('ready')); // ready
}
Never invalidText() => throw const FormatException('Expected text');

String requireText(Object? value) {
  if (value is String) return value;
  invalidText();
}

void main() {
  print(requireText('ready')); // ready
}

82. Why can type promotion fail for fields or captured variables?

Promotion requires evidence that the value being read is still the value that was checked. Mutable fields can change, and getters can compute a different result on each call. A public field can also be overridden by a getter, so making it final does not automatically make it promotable. Modern Dart supports promotion of eligible private final fields, subject to library-wide restrictions.

Captured local variables are another risk when a closure can write them; promotion depends on control-flow analysis proving those writes cannot invalidate the check. A final local snapshot is often the clearest solution. It gives the operation a stable value without scattering null assertions. Here the public nullable field is copied before its length is used.

Dart example

class Profile {
  final String? name;
  Profile(this.name);

  int displayLength() {
    final snapshot = name;
    return snapshot == null ? 0 : snapshot.length;
  }
}

void main() {
  print(Profile('Ada').displayLength()); // 3
  print(Profile(null).displayLength()); // 0
}
class Profile {
  final String? name;
  Profile(this.name);

  int displayLength() {
    final snapshot = name;
    return snapshot == null ? 0 : snapshot.length;
  }
}

void main() {
  print(Profile('Ada').displayLength()); // 3
  print(Profile(null).displayLength()); // 0
}
class Profile {
  final String? name;
  Profile(this.name);

  int displayLength() {
    final snapshot = name;
    return snapshot == null ? 0 : snapshot.length;
  }
}

void main() {
  print(Profile('Ada').displayLength()); // 3
  print(Profile(null).displayLength()); // 0
}

83. How do function subtyping and covariant parameters affect substitutability?

A substitutable function must accept at least the inputs its callers are allowed to supply and return a value compatible with what they expect. Parameter types are contravariant; return types are covariant. A function accepting Object and returning String can therefore serve where a function accepting String and returning Object is required.

An overriding method can use covariant to narrow a parameter, but that deliberately introduces a runtime argument check. Calling it through the broader base-class interface can then throw rather than satisfy every call allowed by that interface. It is useful when a stronger domain invariant exists, not proof of unconditional behavioral substitutability. Generic APIs or separate interfaces often express that relationship more safely.

Dart example

String describe(Object value) => 'value=$value';

void main() {
  Object Function(String) callback = describe;
  print(callback('ok')); // value=ok
}
String describe(Object value) => 'value=$value';

void main() {
  Object Function(String) callback = describe;
  print(callback('ok')); // value=ok
}
String describe(Object value) => 'value=$value';

void main() {
  Object Function(String) callback = describe;
  print(callback('ok')); // value=ok
}

84. When are self-referential generic bounds useful, and what do they not guarantee?

A self-referential bound such as T extends Comparable<T> allows generic code to call operations that consume the same type parameter it produces. It is useful for comparisons, typed builders, and domain operations where plain Object would lose a meaningful relationship.

The bound is a static interface requirement, not a proof that compareTo defines a valid total order. It cannot establish transitivity, consistency with equality, or that a class always supplies its own exact runtime type as the type argument. Those are separate behavioral contracts. The example returns one of its original inputs and uses an explicit domain type, avoiding a cast or a copy. Tests still need to cover equal values and ordering laws.

Dart example

class Rank implements Comparable<Rank> {
  final int value;
  const Rank(this.value);
  @override
  int compareTo(Rank other) => value.compareTo(other.value);
}

T lesser<T extends Comparable<T>>(T a, T b) =>
    a.compareTo(b) <= 0 ? a : b;

void main() {
  print(lesser(const Rank(4), const Rank(2)).value); // 2
}
class Rank implements Comparable<Rank> {
  final int value;
  const Rank(this.value);
  @override
  int compareTo(Rank other) => value.compareTo(other.value);
}

T lesser<T extends Comparable<T>>(T a, T b) =>
    a.compareTo(b) <= 0 ? a : b;

void main() {
  print(lesser(const Rank(4), const Rank(2)).value); // 2
}
class Rank implements Comparable<Rank> {
  final int value;
  const Rank(this.value);
  @override
  int compareTo(Rank other) => value.compareTo(other.value);
}

T lesser<T extends Comparable<T>>(T a, T b) =>
    a.compareTo(b) <= 0 ? a : b;

void main() {
  print(lesser(const Rank(4), const Rank(2)).value); // 2
}

85. How do class modifiers change the compatibility promises of a public package?

Class modifiers define what clients in other libraries may rely on. Changing an unrestricted class to a restrictive modifier can break downstream code even when its methods stay unchanged. These are library boundaries, not merely package boundaries.

Modifier

External-library contract

interface

Clients may implement, but not extend, the class.

base

Clients may extend, but not implement; subtypes preserve the restriction.

final

Clients cannot extend or implement it.

sealed

Direct subtypes are confined to its library, enabling exhaustiveness.

A sealed hierarchy can still expose externally extensible indirect subtypes if its direct subclasses permit that. Adding a new sealed variant can break clients' exhaustive switches. An abstract interface also requires implementers to supply newly added members. Versioning decisions therefore need downstream compile checks, not just the package's own passing tests.

86. Why is an extension type not a runtime security or validation boundary?

An extension type is a static abstraction over a representation object, not a distinct runtime wrapper. Its API can prevent accidental operations in normally typed code, and a constructor can validate ordinary construction. However, runtime type tests and casts use the representation type; they do not certify that a particular validating constructor ran.

Consequently, an extension type is suitable for lightweight identifiers and interoperability, but not for enforcing a security boundary against untrusted values. Validate inputs at the point where they enter the trusted operation. Use a normal class when runtime identity and controlled construction are part of the design, while remembering that authorization still requires explicit checks. The example deliberately demonstrates a constructor check being bypassed by a representation-compatible cast.

Dart example

extension type Positive._(int value) {
  factory Positive(int value) {
    if (value <= 0) throw ArgumentError.value(value, 'value');
    return Positive._(value);
  }
}

void main() {
  print(Positive(3).value); // 3
  final bypassed = (-1) as Positive;
  print(bypassed.value); // -1: the cast did not run the factory.
}
extension type Positive._(int value) {
  factory Positive(int value) {
    if (value <= 0) throw ArgumentError.value(value, 'value');
    return Positive._(value);
  }
}

void main() {
  print(Positive(3).value); // 3
  final bypassed = (-1) as Positive;
  print(bypassed.value); // -1: the cast did not run the factory.
}
extension type Positive._(int value) {
  factory Positive(int value) {
    if (value <= 0) throw ArgumentError.value(value, 'value');
    return Positive._(value);
  }
}

void main() {
  print(Positive(3).value); // 3
  final bypassed = (-1) as Positive;
  print(bypassed.value); // -1: the cast did not run the factory.
}

87. How do exhaustiveness, guarded patterns, and unreachable cases interact?

An exhaustive switch covers every possible value of its scrutinee's static type. Sealed hierarchies, enums, and suitable combinations of patterns make that coverage check useful. A guard adds a runtime condition: matching the pattern is insufficient when the guard is false. A guarded case therefore cannot generally replace an unguarded case needed to cover that type.

Order matters because the first matching case whose guard succeeds wins. An earlier unguarded broad pattern can make a later narrow case unreachable. Put conditional special cases before the broader fallback. Avoid adding a wildcard merely to silence an exhaustiveness error when newly introduced variants should force an explicit decision. Here zero and negative integers still reach the second integer case.

Dart example

String classify(int? value) => switch (value) {
  int n when n > 0 => 'positive',
  int _ => 'non-positive',
  null => 'missing',
};

void main() {
  print(classify(2)); // positive
  print(classify(0)); // non-positive
  print(classify(null)); // missing
}
String classify(int? value) => switch (value) {
  int n when n > 0 => 'positive',
  int _ => 'non-positive',
  null => 'missing',
};

void main() {
  print(classify(2)); // positive
  print(classify(0)); // non-positive
  print(classify(null)); // missing
}
String classify(int? value) => switch (value) {
  int n when n > 0 => 'positive',
  int _ => 'non-positive',
  null => 'missing',
};

void main() {
  print(classify(2)); // positive
  print(classify(0)); // non-positive
  print(classify(null)); // missing
}

88. How do Future(), Future.microtask(), and Future.sync() schedule work and capture errors?

Future(() => work()) schedules the computation through Timer.run, while Future.microtask schedules it in the microtask queue. Microtasks run before the next ordinary event; continually scheduling more can starve event processing. Neither constructor creates a background isolate.

Future.sync invokes the computation immediately. It converts a synchronous throw into a future error and adopts a returned future, making synchronous and asynchronous implementations easier to consume consistently. All three propagate a computation's result or error through the returned future. Attach error handling promptly rather than constructing several failing futures and awaiting them much later. The example's callback order is deterministic: synchronous work first, then the rest of the current stack, then the microtask, then the event callback.

Dart example

import 'dart:async';

Future<void> main() async {
  final event = Future<void>(() => print('event'));
  final micro = Future<void>.microtask(() => print('micro'));
  final sync = Future<void>.sync(() => print('sync'));
  print('end');
  await Future.wait([event, micro, sync]);
  // Expected order: sync, end, micro, event.
}
import 'dart:async';

Future<void> main() async {
  final event = Future<void>(() => print('event'));
  final micro = Future<void>.microtask(() => print('micro'));
  final sync = Future<void>.sync(() => print('sync'));
  print('end');
  await Future.wait([event, micro, sync]);
  // Expected order: sync, end, micro, event.
}
import 'dart:async';

Future<void> main() async {
  final event = Future<void>(() => print('event'));
  final micro = Future<void>.microtask(() => print('micro'));
  final sync = Future<void>.sync(() => print('sync'));
  print('end');
  await Future.wait([event, micro, sync]);
  // Expected order: sync, end, micro, event.
}

89. What can zones intercept, and why can asynchronous errors fail to cross error-zone boundaries?

Zones carry asynchronous context and can customize operations such as timer creation, microtask scheduling, printing, and uncaught-error handling. They are not operating-system sandboxes and cannot make blocking code concurrent. runZonedGuarded installs an error handler for synchronous body failures and uncaught asynchronous failures in its error zone.

Future errors do not cross into a different error zone. Returning a failing future from the guarded zone and awaiting it outside can therefore appear to hang, while the original zone receives the error. Keep the asynchronous operation and its error consumption inside the intended zone, or explicitly translate the outcome through a well-defined result protocol. The small example owns an otherwise uncaught microtask failure; it is not a replacement for local recovery around expected failures.

Dart example

import 'dart:async';

void main() {
  runZonedGuarded(() {
    scheduleMicrotask(() => throw StateError('worker failed'));
  }, (error, stack) {
    print('caught in zone'); // Expected output.
  });
}
import 'dart:async';

void main() {
  runZonedGuarded(() {
    scheduleMicrotask(() => throw StateError('worker failed'));
  }, (error, stack) {
    print('caught in zone'); // Expected output.
  });
}
import 'dart:async';

void main() {
  runZonedGuarded(() {
    scheduleMicrotask(() => throw StateError('worker failed'));
  }, (error, stack) {
    print('caught in zone'); // Expected output.
  });
}

90. How do you adapt a callback API with Completer while preventing double completion?

A Completer bridges a callback contract to one future. Both success and failure must compete for the same terminal state; checking isCompleted prevents duplicate callbacks from completing it twice. Capture synchronous registration errors as well as callback errors, and preserve the supplied stack trace.

The adapter below uses first-terminal-result wins semantics and defers registration to a microtask, allowing the caller to attach its handler immediately. The default asynchronous completer also avoids the reentrancy hazards of Completer.sync. Ignoring duplicate terminal signals is a policy, not evidence that the underlying API is correct; production instrumentation can report that protocol violation. This adapter does not cancel or unsubscribe from the callback source. A resource-owning API needs an explicit cleanup contract in addition to completion.

Dart example

import 'dart:async';

Future<T> fromCallback<T>(
  void Function(void Function(T), void Function(Object, StackTrace)) start,
) {
  final result = Completer<T>();
  void fail(Object error, StackTrace stack) {
    if (!result.isCompleted) result.completeError(error, stack);
  }
  scheduleMicrotask(() {
    try {
      start((value) {
        if (!result.isCompleted) result.complete(value);
      }, fail);
    } catch (error, stack) {
      fail(error, stack);
    }
  });
  return result.future;
}

Future<void> main() async {
  final value = await fromCallback<int>((success, failure) {
    success(7);
    success(8); // Duplicate ignored by this contract.
  });
  print(value); // 7
}
import 'dart:async';

Future<T> fromCallback<T>(
  void Function(void Function(T), void Function(Object, StackTrace)) start,
) {
  final result = Completer<T>();
  void fail(Object error, StackTrace stack) {
    if (!result.isCompleted) result.completeError(error, stack);
  }
  scheduleMicrotask(() {
    try {
      start((value) {
        if (!result.isCompleted) result.complete(value);
      }, fail);
    } catch (error, stack) {
      fail(error, stack);
    }
  });
  return result.future;
}

Future<void> main() async {
  final value = await fromCallback<int>((success, failure) {
    success(7);
    success(8); // Duplicate ignored by this contract.
  });
  print(value); // 7
}
import 'dart:async';

Future<T> fromCallback<T>(
  void Function(void Function(T), void Function(Object, StackTrace)) start,
) {
  final result = Completer<T>();
  void fail(Object error, StackTrace stack) {
    if (!result.isCompleted) result.completeError(error, stack);
  }
  scheduleMicrotask(() {
    try {
      start((value) {
        if (!result.isCompleted) result.complete(value);
      }, fail);
    } catch (error, stack) {
      fail(error, stack);
    }
  });
  return result.future;
}

Future<void> main() async {
  final value = await fromCallback<int>((success, failure) {
    success(7);
    success(8); // Duplicate ignored by this contract.
  });
  print(value); // 7
}

91. How do you design cooperative cancellation when Future itself has no cancel method?

A future represents eventual completion; it does not provide a universal way to stop the computation producing it. timeout stops waiting for a result but does not cancel the source operation. A cancellation contract must specify who requests cancellation, where work checks it, and which underlying resources can actually be interrupted.

This token stops the loop at explicit checkpoints and reports cancellation distinctly from failure. The scheduled delay still completes; the token cannot preempt synchronous CPU work or abort arbitrary I/O. For a network operation, connect the token to that client's supported abort mechanism and continue observing completion errors. Put owned-resource cleanup in finally. Keep cancellation idempotent, and define whether partially completed side effects remain or require compensation.

Dart example

import 'dart:async';

class Cancelled implements Exception {}
class CancelToken {
  bool _cancelled = false;
  void cancel() => _cancelled = true;
  void check() {
    if (_cancelled) throw Cancelled();
  }
}

Future<int> count(CancelToken token) async {
  var total = 0;
  for (var i = 0; i < 10; i++) {
    token.check();
    await Future<void>.delayed(Duration.zero);
    token.check();
    total++;
  }
  return total;
}

Future<void> main() async {
  final token = CancelToken();
  final pending = count(token);
  token.cancel();
  try {
    await pending;
  } on Cancelled {
    print('cancelled'); // Expected output.
  }
}
import 'dart:async';

class Cancelled implements Exception {}
class CancelToken {
  bool _cancelled = false;
  void cancel() => _cancelled = true;
  void check() {
    if (_cancelled) throw Cancelled();
  }
}

Future<int> count(CancelToken token) async {
  var total = 0;
  for (var i = 0; i < 10; i++) {
    token.check();
    await Future<void>.delayed(Duration.zero);
    token.check();
    total++;
  }
  return total;
}

Future<void> main() async {
  final token = CancelToken();
  final pending = count(token);
  token.cancel();
  try {
    await pending;
  } on Cancelled {
    print('cancelled'); // Expected output.
  }
}
import 'dart:async';

class Cancelled implements Exception {}
class CancelToken {
  bool _cancelled = false;
  void cancel() => _cancelled = true;
  void check() {
    if (_cancelled) throw Cancelled();
  }
}

Future<int> count(CancelToken token) async {
  var total = 0;
  for (var i = 0; i < 10; i++) {
    token.check();
    await Future<void>.delayed(Duration.zero);
    token.check();
    total++;
  }
  return total;
}

Future<void> main() async {
  final token = CancelToken();
  final pending = count(token);
  token.cancel();
  try {
    await pending;
  } on Cancelled {
    print('cancelled'); // Expected output.
  }
}

92. How would you implement bounded asynchronous concurrency while preserving input order?

Starting every operation and passing its future to Future.wait does not limit concurrency. A worker pool instead claims at most one new index per available worker. Claiming the index before await is safe on one isolate because another callback cannot interleave inside that synchronous segment.

This implementation snapshots the input, preserves result order, and rejects a non-positive limit. On the first observed failure, workers stop claiming new items; already-started operations are awaited and their errors observed before the original failure is rethrown with its stack. This is not cancellation, and an operation that never settles can still stall completion. Result storage costs O(n), while active operations are bounded by the smaller of the limit and input length. Nullable result types are supported.

Dart example

import 'dart:async';

Future<List<R>> mapBounded<T, R>(
  List<T> input, int limit, Future<R> Function(T) run,
) async {
  if (limit <= 0) throw ArgumentError.value(limit, 'limit');
  final items = List<T>.of(input);
  final results = List<R?>.filled(items.length, null);
  var next = 0;
  var failed = false;
  Object? firstError;
  StackTrace? firstStack;

  Future<void> worker() async {
    while (!failed && next < items.length) {
      final index = next++;
      try {
        results[index] = await run(items[index]);
      } catch (error, stack) {
        if (!failed) {
          failed = true;
          firstError = error;
          firstStack = stack;
        }
      }
    }
  }

  final count = limit < items.length ? limit : items.length;
  await Future.wait(List.generate(count, (_) => worker()));
  if (failed) Error.throwWithStackTrace(firstError!, firstStack!);
  return [for (final result in results) result as R];
}

Future<void> main() async {
  print(await mapBounded<int, int>([3, 1, 2], 2, (n) async => n * n));
  // [9, 1, 4]
  print(await mapBounded<int, int>([], 2, (n) async => n)); // []
}
import 'dart:async';

Future<List<R>> mapBounded<T, R>(
  List<T> input, int limit, Future<R> Function(T) run,
) async {
  if (limit <= 0) throw ArgumentError.value(limit, 'limit');
  final items = List<T>.of(input);
  final results = List<R?>.filled(items.length, null);
  var next = 0;
  var failed = false;
  Object? firstError;
  StackTrace? firstStack;

  Future<void> worker() async {
    while (!failed && next < items.length) {
      final index = next++;
      try {
        results[index] = await run(items[index]);
      } catch (error, stack) {
        if (!failed) {
          failed = true;
          firstError = error;
          firstStack = stack;
        }
      }
    }
  }

  final count = limit < items.length ? limit : items.length;
  await Future.wait(List.generate(count, (_) => worker()));
  if (failed) Error.throwWithStackTrace(firstError!, firstStack!);
  return [for (final result in results) result as R];
}

Future<void> main() async {
  print(await mapBounded<int, int>([3, 1, 2], 2, (n) async => n * n));
  // [9, 1, 4]
  print(await mapBounded<int, int>([], 2, (n) async => n)); // []
}
import 'dart:async';

Future<List<R>> mapBounded<T, R>(
  List<T> input, int limit, Future<R> Function(T) run,
) async {
  if (limit <= 0) throw ArgumentError.value(limit, 'limit');
  final items = List<T>.of(input);
  final results = List<R?>.filled(items.length, null);
  var next = 0;
  var failed = false;
  Object? firstError;
  StackTrace? firstStack;

  Future<void> worker() async {
    while (!failed && next < items.length) {
      final index = next++;
      try {
        results[index] = await run(items[index]);
      } catch (error, stack) {
        if (!failed) {
          failed = true;
          firstError = error;
          firstStack = stack;
        }
      }
    }
  }

  final count = limit < items.length ? limit : items.length;
  await Future.wait(List.generate(count, (_) => worker()));
  if (failed) Error.throwWithStackTrace(firstError!, firstStack!);
  return [for (final result in results) result as R];
}

Future<void> main() async {
  print(await mapBounded<int, int>([3, 1, 2], 2, (n) async => n * n));
  // [9, 1, 4]
  print(await mapBounded<int, int>([], 2, (n) async => n)); // []
}

93. How do stream pause, buffering, and cancellation affect backpressure?

Pausing a subscription stops delivery to that listener; it does not guarantee that the producer stops generating events. A single-subscription source can honor pause notifications, whereas a paused broadcast subscription generally buffers its own events without stopping other listeners. An unbounded buffer can therefore move the overload problem rather than solve it.

Use an explicit policy: propagate backpressure where supported, bound a queue, reject work, or deliberately drop replaceable events. An await for loop with awaited processing handles events sequentially; an asynchronous callback passed to listen is not automatically awaited by the stream. Cancellation stops further delivery, and its returned future represents source cleanup. Await it before using or deleting resources whose release depends on cancellation. The example deliberately preserves processing order.

Dart example

import 'dart:async';

Future<void> consume(
  Stream<int> source, Future<void> Function(int) save,
) async {
  await for (final value in source) {
    await save(value);
  }
}

Future<void> main() async {
  final saved = <int>[];
  await consume(Stream.fromIterable([1, 2, 3]), (value) async {
    saved.add(value)

import 'dart:async';

Future<void> consume(
  Stream<int> source, Future<void> Function(int) save,
) async {
  await for (final value in source) {
    await save(value);
  }
}

Future<void> main() async {
  final saved = <int>[];
  await consume(Stream.fromIterable([1, 2, 3]), (value) async {
    saved.add(value)

import 'dart:async';

Future<void> consume(
  Stream<int> source, Future<void> Function(int) save,
) async {
  await for (final value in source) {
    await save(value);
  }
}

Future<void> main() async {
  final saved = <int>[];
  await consume(Stream.fromIterable([1, 2, 3]), (value) async {
    saved.add(value)

94. How do you design retries with backoff without hiding permanent errors or duplicating side effects?

Retry only failures classified as transient, with a maximum attempt count and an overall deadline. Authentication failures, malformed input, and programming errors should not become long retry loops. Capped exponential backoff with jitter spreads competing clients' retry traffic; server-provided retry instructions may impose a different minimum delay.

A timeout does not establish that a write failed: the server may have committed it before the reply was lost. Retrying side effects requires an idempotency key or a deduplication/reconciliation protocol, not merely a catch block. The example supplies classification explicitly, preserves the final error with rethrow, and uses bounded full jitter. Its operation must already be safe to retry. Production cancellation and deadlines must also cover waiting between attempts, not just individual requests.

Dart example

import 'dart:async';
import 'dart:math';

Future<T> retry<T>(Future<T> Function() operation, {
  required bool Function(Object) transient,
  int maxAttempts = 3,
}) async {
  if (maxAttempts < 1) throw ArgumentError.value(maxAttempts);
  final random = Random();
  var capMs = 100;
  for (var attempt = 1; ; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt >= maxAttempts || !transient(error)) rethrow;
      await Future<void>.delayed(
        Duration(milliseconds: random.nextInt(capMs + 1)),
      );
      capMs = capMs >= 1000 ? 2000 : capMs * 2;
    }
  }
}

Future<void> main() async {
  var attempts = 0;
  final value = await retry(() async {
    if (++attempts == 1) throw TimeoutException('temporary');
    return 42;
  }, transient: (error) => error is TimeoutException);
  print('$value after $attempts attempts'); // 42 after 2 attempts
}
import 'dart:async';
import 'dart:math';

Future<T> retry<T>(Future<T> Function() operation, {
  required bool Function(Object) transient,
  int maxAttempts = 3,
}) async {
  if (maxAttempts < 1) throw ArgumentError.value(maxAttempts);
  final random = Random();
  var capMs = 100;
  for (var attempt = 1; ; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt >= maxAttempts || !transient(error)) rethrow;
      await Future<void>.delayed(
        Duration(milliseconds: random.nextInt(capMs + 1)),
      );
      capMs = capMs >= 1000 ? 2000 : capMs * 2;
    }
  }
}

Future<void> main() async {
  var attempts = 0;
  final value = await retry(() async {
    if (++attempts == 1) throw TimeoutException('temporary');
    return 42;
  }, transient: (error) => error is TimeoutException);
  print('$value after $attempts attempts'); // 42 after 2 attempts
}
import 'dart:async';
import 'dart:math';

Future<T> retry<T>(Future<T> Function() operation, {
  required bool Function(Object) transient,
  int maxAttempts = 3,
}) async {
  if (maxAttempts < 1) throw ArgumentError.value(maxAttempts);
  final random = Random();
  var capMs = 100;
  for (var attempt = 1; ; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt >= maxAttempts || !transient(error)) rethrow;
      await Future<void>.delayed(
        Duration(milliseconds: random.nextInt(capMs + 1)),
      );
      capMs = capMs >= 1000 ? 2000 : capMs * 2;
    }
  }
}

Future<void> main() async {
  var attempts = 0;
  final value = await retry(() async {
    if (++attempts == 1) throw TimeoutException('temporary');
    return 42;
  }, transient: (error) => error is TimeoutException);
  print('$value after $attempts attempts'); // 42 after 2 attempts
}

95. How can overlapping asynchronous requests produce stale results on a single isolate?

A single isolate executes one synchronous segment at a time, but await allows other work to run before the original operation resumes. Two searches can therefore start in order A, B and complete in order B, A. Applying every completion blindly lets the older response overwrite the newer state without any simultaneous memory access.

A monotonically increasing generation identifies the most recently requested operation. Apply a result only when its generation still matches. This suppresses stale results but does not cancel the old request or erase its side effects. Errors still need a caller-owned policy; the example propagates them to the returned futures. Disposal or explicit invalidation should also advance the generation when no in-flight result remains relevant. Controlled completers demonstrate the race without timing-dependent sleeps.

Dart example

import 'dart:async';

class Latest<T> {
  int _generation = 0;
  T? value;
  Future<void> update(Future<T> Function() load) async {
    final generation = ++_generation;
    final result = await load();
    if (generation == _generation) value = result;
  }
}

Future<void> main() async {
  final state = Latest<String>();
  final old = Completer<String>();
  final recent = Completer<String>();
  final first = state.update(() => old.future);
  final second = state.update(() => recent.future);
  recent.complete('new');
  await second;
  old.complete('old');
  await first;
  print(state.value); // new
}
import 'dart:async';

class Latest<T> {
  int _generation = 0;
  T? value;
  Future<void> update(Future<T> Function() load) async {
    final generation = ++_generation;
    final result = await load();
    if (generation == _generation) value = result;
  }
}

Future<void> main() async {
  final state = Latest<String>();
  final old = Completer<String>();
  final recent = Completer<String>();
  final first = state.update(() => old.future);
  final second = state.update(() => recent.future);
  recent.complete('new');
  await second;
  old.complete('old');
  await first;
  print(state.value); // new
}
import 'dart:async';

class Latest<T> {
  int _generation = 0;
  T? value;
  Future<void> update(Future<T> Function() load) async {
    final generation = ++_generation;
    final result = await load();
    if (generation == _generation) value = result;
  }
}

Future<void> main() async {
  final state = Latest<String>();
  final old = Completer<String>();
  final recent = Completer<String>();
  final first = state.update(() => old.future);
  final second = state.update(() => recent.future);
  recent.complete('new');
  await second;
  old.complete('old');
  await first;
  print(state.value); // new
}

96. When should CPU-bound work use Isolate.run, and what changes on the web?

Use Isolate.run for a sufficiently expensive CPU-bound task that would otherwise block its caller's isolate, such as parsing a large payload or transforming an image buffer. Ordinary asynchronous I/O already yields while waiting; moving every request into a fresh isolate can add startup and communication costs without improving throughput.

The computation runs in a new isolate, and its result or failure completes the returned future. Both the computation's captured state and its result must be sendable. Native isolates are not supported by Dart's web platform; a browser worker solution requires an appropriate web-specific implementation, not an assumption that the same call creates a worker. Benchmark offloading overhead and responsiveness on the actual target. This example is a native command-line program using a top-level computation.

Dart example

import 'dart:isolate';

int sumSquares() {
  var total = 0;
  for (var i = 1; i <= 10000; i++) {
    total += i * i;
  }
  return total;
}

Future<void> main() async {
  print(await Isolate.run(sumSquares)); // 333383335000
}
import 'dart:isolate';

int sumSquares() {
  var total = 0;
  for (var i = 1; i <= 10000; i++) {
    total += i * i;
  }
  return total;
}

Future<void> main() async {
  print(await Isolate.run(sumSquares)); // 333383335000
}
import 'dart:isolate';

int sumSquares() {
  var total = 0;
  for (var i = 1; i <= 10000; i++) {
    total += i * i;
  }
  return total;
}

Future<void> main() async {
  print(await Isolate.run(sumSquares)); // 333383335000
}

97. Which objects can cross isolate boundaries, and why can captured closures be a problem?

Sendability depends on how the isolates were created and on the entire reachable object graph. Isolates sharing code through Isolate.spawn can exchange many ordinary Dart objects, not just JSON-compatible values. Exceptions include receive ports, sockets and other native-resource objects, finalizers, and explicitly unsendable classes. spawnUri has a narrower permitted set.

Mutable objects are generally copied; recognized immutable objects such as strings can be shared. Sending a small container can still be expensive if it references a large graph. Closures are especially subtle because their captured context can include more state than the visible expression appears to need, causing extra copying or a sendability failure. Prefer top-level entry points and deliberately small message objects; isolate a closure-producing helper from unrelated resources when using Isolate.run.

Dart example

import 'dart:convert';
import 'dart:isolate';

// This scope captures only the supplied, sendable map.
Future<String> encodeInWorker(Map<String, int> data) =>
    Isolate.run(() => jsonEncode(data));

Future<void> main() async {
  print(await encodeInWorker({'count': 3})); // {"count":3}
}
import 'dart:convert';
import 'dart:isolate';

// This scope captures only the supplied, sendable map.
Future<String> encodeInWorker(Map<String, int> data) =>
    Isolate.run(() => jsonEncode(data));

Future<void> main() async {
  print(await encodeInWorker({'count': 3})); // {"count":3}
}
import 'dart:convert';
import 'dart:isolate';

// This scope captures only the supplied, sendable map.
Future<String> encodeInWorker(Map<String, int> data) =>
    Isolate.run(() => jsonEncode(data));

Future<void> main() async {
  print(await encodeInWorker({'count': 3})); // {"count":3}
}

98. How do you structure a long-lived isolate's request-response protocol and shutdown?

A reusable worker needs a startup handshake, explicit message shapes, request identifiers, success/error replies, and a shutdown contract. Keep a parent-side pending-request map for concurrent requests, reject unknown or duplicate replies, and fail pending callers if the worker dies. Bound the pending queue rather than letting faster producers accumulate unlimited work.

The native example demonstrates sequential requests with record messages, a stop acknowledgment, and a timeout-backed cleanup path. StreamIterator keeps one subscription across the handshake and later replies. Acknowledging stop is a protocol event, not proof of a successful operating-system exit; a production parent should also observe exit and uncaught-error notifications. A timed-out request is not automatically canceled. Killing the isolate in finally is fallback containment, not graceful cleanup of its external side effects.

Dart example

import 'dart:async';
import 'dart:isolate';

void worker(SendPort parent) {
  final inbox = ReceivePort();
  parent.send(inbox.sendPort);
  inbox.listen((message) {
    final (id, operation, value) = message as (int, String, int?);
    if (operation == 'square' && value != null) {
      parent.send((id, 'ok', value * value));
    } else if (operation == 'stop') {
      inbox.close();
      parent.send((id, 'stopped', null));
    } else {
      parent.send((id, 'error', 'Invalid request'));
    }
  });
}

Future<Object?> nextMessage(StreamIterator<Object?> messages) async {
  if (!await messages.moveNext()) throw StateError('Worker closed');
  return messages.current;
}

Future<void> main() async {
  final inbox = ReceivePort();
  final messages = StreamIterator<Object?>(inbox);
  Isolate? isolate;
  Future<Object?> next() => nextMessage(messages)
      .timeout(const Duration(seconds: 5));
  try {
    isolate = await Isolate.spawn(worker, inbox.sendPort);
    final commands = await next() as SendPort;
    commands.send((1, 'square', 6));
    print(await next()); // (1, ok, 36)
    commands.send((2, 'stop', null));
    print(await next()); // (2, stopped, null)
  } finally {
    isolate?.kill(priority: Isolate.immediate);
    await messages.cancel();
    inbox.close();
  }
}
import 'dart:async';
import 'dart:isolate';

void worker(SendPort parent) {
  final inbox = ReceivePort();
  parent.send(inbox.sendPort);
  inbox.listen((message) {
    final (id, operation, value) = message as (int, String, int?);
    if (operation == 'square' && value != null) {
      parent.send((id, 'ok', value * value));
    } else if (operation == 'stop') {
      inbox.close();
      parent.send((id, 'stopped', null));
    } else {
      parent.send((id, 'error', 'Invalid request'));
    }
  });
}

Future<Object?> nextMessage(StreamIterator<Object?> messages) async {
  if (!await messages.moveNext()) throw StateError('Worker closed');
  return messages.current;
}

Future<void> main() async {
  final inbox = ReceivePort();
  final messages = StreamIterator<Object?>(inbox);
  Isolate? isolate;
  Future<Object?> next() => nextMessage(messages)
      .timeout(const Duration(seconds: 5));
  try {
    isolate = await Isolate.spawn(worker, inbox.sendPort);
    final commands = await next() as SendPort;
    commands.send((1, 'square', 6));
    print(await next()); // (1, ok, 36)
    commands.send((2, 'stop', null));
    print(await next()); // (2, stopped, null)
  } finally {
    isolate?.kill(priority: Isolate.immediate);
    await messages.cancel();
    inbox.close();
  }
}
import 'dart:async';
import 'dart:isolate';

void worker(SendPort parent) {
  final inbox = ReceivePort();
  parent.send(inbox.sendPort);
  inbox.listen((message) {
    final (id, operation, value) = message as (int, String, int?);
    if (operation == 'square' && value != null) {
      parent.send((id, 'ok', value * value));
    } else if (operation == 'stop') {
      inbox.close();
      parent.send((id, 'stopped', null));
    } else {
      parent.send((id, 'error', 'Invalid request'));
    }
  });
}

Future<Object?> nextMessage(StreamIterator<Object?> messages) async {
  if (!await messages.moveNext()) throw StateError('Worker closed');
  return messages.current;
}

Future<void> main() async {
  final inbox = ReceivePort();
  final messages = StreamIterator<Object?>(inbox);
  Isolate? isolate;
  Future<Object?> next() => nextMessage(messages)
      .timeout(const Duration(seconds: 5));
  try {
    isolate = await Isolate.spawn(worker, inbox.sendPort);
    final commands = await next() as SendPort;
    commands.send((1, 'square', 6));
    print(await next()); // (1, ok, 36)
    commands.send((2, 'stop', null));
    print(await next()); // (2, stopped, null)
  } finally {
    isolate?.kill(priority: Isolate.immediate);
    await messages.cancel();
    inbox.close();
  }
}

99. What does TransferableTypedData transfer, and what happens to ownership afterward?

TransferableTypedData packages byte data so its transferable storage can move between isolates without copying that storage on each send. Creating it from existing typed-data lists still takes time proportional to the byte count; it is not a zero-cost way to create or serialize a buffer.

After transfer, the sender's transferable handle can no longer be materialized. The receiving handle can materialize the bytes once into a ByteBuffer. The original lists used to construct the transferable are separate and do not become universally unusable. Treat the transferable as a move-only payload, document which side owns it, and avoid retaining redundant source buffers unnecessarily. The native example uses a local receive port to demonstrate the transfer contract; a worker's send port uses the same ownership rule.

Dart example

import 'dart:isolate';
import 'dart:typed_data';

Future<void> main() async {
  final original = Uint8List.fromList([1, 2, 3]);
  final payload = TransferableTypedData.fromList([original]);
  final inbox = ReceivePort();
  try {
    final received = inbox.first;
    inbox.sendPort.send(payload);
    final moved = await received as TransferableTypedData;
    print(moved.materialize().asUint8List()); // [1, 2, 3]
    print(original[0]); // 1: the source list is still usable.
    // Do not materialize payload after sending it.
    // Do not materialize moved a second time.
  } finally {
    inbox.close();
  }
}
import 'dart:isolate';
import 'dart:typed_data';

Future<void> main() async {
  final original = Uint8List.fromList([1, 2, 3]);
  final payload = TransferableTypedData.fromList([original]);
  final inbox = ReceivePort();
  try {
    final received = inbox.first;
    inbox.sendPort.send(payload);
    final moved = await received as TransferableTypedData;
    print(moved.materialize().asUint8List()); // [1, 2, 3]
    print(original[0]); // 1: the source list is still usable.
    // Do not materialize payload after sending it.
    // Do not materialize moved a second time.
  } finally {
    inbox.close();
  }
}
import 'dart:isolate';
import 'dart:typed_data';

Future<void> main() async {
  final original = Uint8List.fromList([1, 2, 3]);
  final payload = TransferableTypedData.fromList([original]);
  final inbox = ReceivePort();
  try {
    final received = inbox.first;
    inbox.sendPort.send(payload);
    final moved = await received as TransferableTypedData;
    print(moved.materialize().asUint8List()); // [1, 2, 3]
    print(original[0]); // 1: the source list is still usable.
    // Do not materialize payload after sending it.
    // Do not materialize moved a second time.
  } finally {
    inbox.close();
  }
}

100. How should a parent isolate observe worker failures and unexpected exits?

Register onError and onExit when spawning, or start paused and install listeners before resuming. Registering afterward can miss a worker that fails immediately. Uncaught-error notifications contain an error string and a stack-trace string or null; they do not preserve an arbitrary original exception object.

An exit notification only says the worker terminated, not whether every request succeeded. Maintain terminal state so errors, exit, cancellation, and timeouts cannot complete the same pending request twice. Fail all outstanding requests on unexpected termination and reject new ones. The native example observes a fatal startup error and the eventual exit on one port, with a bounded wait and cleanup. It logs the failure for demonstration; a request-serving parent must additionally propagate it to callers.

Dart example

import 'dart:async';
import 'dart:isolate';

void crash(Object? _) => throw StateError('worker failed');

Future<void> main() async {
  final events = ReceivePort();
  final exited = Completer<void>();
  final subscription = events.listen((message) {
    if (message == null) {
      if (!exited.isCompleted) exited.complete();
    } else {
      final details = message as List;
      print('worker error: ${details[0]}');
    }
  });
  Isolate? isolate;
  try {
    isolate = await Isolate.spawn<Object?>(crash, null,
        onError: events.sendPort, onExit: events.sendPort,
        errorsAreFatal: true);
    await exited.future.timeout(const Duration(seconds: 5));
    print('worker exited');
  } finally {
    isolate?.kill(priority: Isolate.immediate);
    await subscription.cancel();
    events.close();
  }
}
import 'dart:async';
import 'dart:isolate';

void crash(Object? _) => throw StateError('worker failed');

Future<void> main() async {
  final events = ReceivePort();
  final exited = Completer<void>();
  final subscription = events.listen((message) {
    if (message == null) {
      if (!exited.isCompleted) exited.complete();
    } else {
      final details = message as List;
      print('worker error: ${details[0]}');
    }
  });
  Isolate? isolate;
  try {
    isolate = await Isolate.spawn<Object?>(crash, null,
        onError: events.sendPort, onExit: events.sendPort,
        errorsAreFatal: true);
    await exited.future.timeout(const Duration(seconds: 5));
    print('worker exited');
  } finally {
    isolate?.kill(priority: Isolate.immediate);
    await subscription.cancel();
    events.close();
  }
}
import 'dart:async';
import 'dart:isolate';

void crash(Object? _) => throw StateError('worker failed');

Future<void> main() async {
  final events = ReceivePort();
  final exited = Completer<void>();
  final subscription = events.listen((message) {
    if (message == null) {
      if (!exited.isCompleted) exited.complete();
    } else {
      final details = message as List;
      print('worker error: ${details[0]}');
    }
  });
  Isolate? isolate;
  try {
    isolate = await Isolate.spawn<Object?>(crash, null,
        onError: events.sendPort, onExit: events.sendPort,
        errorsAreFatal: true);
    await exited.future.timeout(const Duration(seconds: 5));
    print('worker exited');
  } finally {
    isolate?.kill(priority: Isolate.immediate);
    await subscription.cancel();
    events.close();
  }
}

101. How do you profile Dart code without confusing JIT warm-up with AOT performance?

Profile the artifact and workload that matter. A development VM run includes JIT compilation and optimization; early iterations can measure warm-up rather than steady-state execution. An AOT executable has a different startup and optimization model, so a warmed JIT result is not evidence of AOT throughput or latency.

Separate cold-start, steady-state CPU, allocation, and I/O measurements. Fix input size and distribution, record the SDK, target, architecture, and build command, and sample multiple independent runs. Use DevTools CPU profiles to identify expensive stacks rather than guessing from elapsed time alone. Compare baseline and changed code under the same conditions, then recheck end-to-end behavior. For example, an optimization that reduces parser CPU but increases allocations may improve a microbenchmark while worsening request latency under garbage-collection pressure.

102. How can a garbage-collected Dart program still retain memory unnecessarily?

Garbage collection reclaims unreachable objects, not objects the application no longer considers useful. A global cache, active timer, stream subscription, or closure can keep an entire object graph reachable. A small retained view or callback can therefore preserve a much larger backing structure. Native memory and open resources also need their own ownership rules.

Investigate growth after repeated lifecycle cycles, not one transient peak. Compare heap snapshots and inspect retaining paths from long-lived roots. Remove completed entries, bound caches, cancel owned subscriptions and timers, and release references when a component is disposed. The example cancels its subscription before clearing buffered data, preventing later events from repopulating it. The caller still owns the source stream; disposing this consumer must not indiscriminately close a shared producer.

Dart example

import 'dart:async';

class Recorder {
  final values = <int>[];
  late final StreamSubscription<int> _subscription;
  Recorder(Stream<int> source) {
    _subscription = source.listen(values.add);
  }
  Future<void> dispose() async {
    await _subscription.cancel();
    values.clear();
  }
}

Future<void> main() async {
  final 

import 'dart:async';

class Recorder {
  final values = <int>[];
  late final StreamSubscription<int> _subscription;
  Recorder(Stream<int> source) {
    _subscription = source.listen(values.add);
  }
  Future<void> dispose() async {
    await _subscription.cancel();
    values.clear();
  }
}

Future<void> main() async {
  final 

import 'dart:async';

class Recorder {
  final values = <int>[];
  late final StreamSubscription<int> _subscription;
  Recorder(Stream<int> source) {
    _subscription = source.listen(values.add);
  }
  Future<void> dispose() async {
    await _subscription.cancel();
    values.clear();
  }
}

Future<void> main() async {
  final 

103. How do collection choice and equality behavior affect algorithmic cost?

Collection complexity depends on the operation and the implementation. Repeated List.contains checks can turn deduplication into O(nยฒ) work because each lookup scans previous values. A hash set gives expected O(1) membership operations with well-distributed, stable hashes, producing expected O(n) deduplication and O(u) extra storage for u unique values.

Those bounds assume hashing and equality themselves have bounded cost. Deep equality, expensive hash computation, or pathological collisions can change the effective cost substantially. Equal keys must have equal hashes, and equality-relevant state must not mutate while a key is stored. Choose ordered collections when iteration order matters instead of relying on accidental behavior. This example retains the first occurrence of each value; it does not sort the result.

Dart example

List<T> unique<T>(Iterable<T> input) {
  final seen = <T>{};
  return [for (final value in input) if (seen.add(value)) value];
}

void main() {
  print(unique(['b', 'a', 'b', 'c']))

List<T> unique<T>(Iterable<T> input) {
  final seen = <T>{};
  return [for (final value in input) if (seen.add(value)) value];
}

void main() {
  print(unique(['b', 'a', 'b', 'c']))

List<T> unique<T>(Iterable<T> input) {
  final seen = <T>{};
  return [for (final value in input) if (seen.add(value)) value];
}

void main() {
  print(unique(['b', 'a', 'b', 'c']))

104. How do integer precision and bitwise behavior differ between native and JavaScript targets?

Native Dart integers use signed 64-bit two's-complement arithmetic, with wrapping on overflow. JavaScript-compiled Dart represents numbers through JavaScript's double-precision number representation. Every integer from โˆ’2^53 through 2^53 is representable, but adjacent integers beyond that range are not all distinct; some larger integers remain exactly representable.

JavaScript-target bitwise operations truncate operands to 32-bit integers, unlike native 64-bit operations. Consequently, an apparently harmless mask or increment can produce different results across targets. These are specifically JavaScript-target constraints, not a blanket statement about every web compilation backend. Use BigInt for exact larger arithmetic and strings for transporting identifiers that must not be rounded by JSON consumers. Test boundary values on each supported target rather than treating VM-only tests as portability evidence.

Dart example

void main() {
  final n = int.parse('9007199254740992');
  print(n == n + 1); // Native: false. JavaScript target: true.
  final highBit = int.parse('4294967296');
  print(highBit | 0); // Native: 4294967296. JavaScript target: 0.
  final exact = BigInt.parse('9007199254740992');
  print(exact + BigInt.one); // 9007199254740993 on both targets.
}
void main() {
  final n = int.parse('9007199254740992');
  print(n == n + 1); // Native: false. JavaScript target: true.
  final highBit = int.parse('4294967296');
  print(highBit | 0); // Native: 4294967296. JavaScript target: 0.
  final exact = BigInt.parse('9007199254740992');
  print(exact + BigInt.one); // 9007199254740993 on both targets.
}
void main() {
  final n = int.parse('9007199254740992');
  print(n == n + 1); // Native: false. JavaScript target: true.
  final highBit = int.parse('4294967296');
  print(highBit | 0); // Native: 4294967296. JavaScript target: 0.
  final exact = BigInt.parse('9007199254740992');
  print(exact + BigInt.one); // 9007199254740993 on both targets.
}

105. What pitfalls arise with floating-point equality, NaN, infinity, and monetary values?

Binary floating-point cannot represent every decimal fraction exactly, so mathematically equivalent decimal calculations can produce slightly different results. Approximate comparison should use a domain-appropriate absolute tolerance near zero and relative tolerance at larger magnitudes, not one arbitrary epsilon for every application.

NaN is unequal to itself and ordinary ordered comparisons with it are false. Infinity requires explicit treatment; subtracting equal infinities produces NaN, which can break a naรฏve tolerance check. The example handles exact equality first, rejects non-finite mismatches, and scales relative comparison to avoid overflow. Approximate equality is not generally transitive, so it is unsuitable as a hash-map key equivalence relation. Monetary values need an explicit scale and rounding policy, usually integer minor units or decimal arithmetic, with overflow and JavaScript precision limits considered separately.

Dart example

import 'dart:math';

bool close(double a, double b, {double absolute = 1e-12,
    double relative = 1e-9}) {
  if (!absolute.isFinite || !relative.isFinite ||
      absolute < 0 || relative < 0) {
    throw ArgumentError('Tolerances must be finite and non-negative');
  }
  if (a == b) return true;
  if (!a.isFinite || !b.isFinite) return false;
  if ((a - b).abs() <= absolute) return true;
  final scale = max(a.abs(), b.abs()); // Nonzero after equality check.
  return (a / scale - b / scale).abs() <= relative;
}

void main() {
  print(close(0.1 + 0.2, 0.3)); // true
  print(close(double.nan, double.nan)); // false
  print(close(double.infinity, double.infinity)); // true
  print(close(1.7e308, -1.7e308, relative: 1.5)); // false
}
import 'dart:math';

bool close(double a, double b, {double absolute = 1e-12,
    double relative = 1e-9}) {
  if (!absolute.isFinite || !relative.isFinite ||
      absolute < 0 || relative < 0) {
    throw ArgumentError('Tolerances must be finite and non-negative');
  }
  if (a == b) return true;
  if (!a.isFinite || !b.isFinite) return false;
  if ((a - b).abs() <= absolute) return true;
  final scale = max(a.abs(), b.abs()); // Nonzero after equality check.
  return (a / scale - b / scale).abs() <= relative;
}

void main() {
  print(close(0.1 + 0.2, 0.3)); // true
  print(close(double.nan, double.nan)); // false
  print(close(double.infinity, double.infinity)); // true
  print(close(1.7e308, -1.7e308, relative: 1.5)); // false
}
import 'dart:math';

bool close(double a, double b, {double absolute = 1e-12,
    double relative = 1e-9}) {
  if (!absolute.isFinite || !relative.isFinite ||
      absolute < 0 || relative < 0) {
    throw ArgumentError('Tolerances must be finite and non-negative');
  }
  if (a == b) return true;
  if (!a.isFinite || !b.isFinite) return false;
  if ((a - b).abs() <= absolute) return true;
  final scale = max(a.abs(), b.abs()); // Nonzero after equality check.
  return (a / scale - b / scale).abs() <= relative;
}

void main() {
  print(close(0.1 + 0.2, 0.3)); // true
  print(close(double.nan, double.nan)); // false
  print(close(double.infinity, double.infinity)); // true
  print(close(1.7e308, -1.7e308, relative: 1.5)); // false
}

106. How would you reverse user-perceived characters without splitting surrogate pairs or combining sequences?

A Dart string is indexed by UTF-16 code units. Reversing code units can split a surrogate pair; reversing runes preserves code points but can still separate combining marks, emoji modifiers, or joined emoji sequences. User-perceived characters are better approximated by Unicode extended grapheme clusters.

Use the characters package to segment those clusters, then reverse their order without changing each cluster internally. Add the dependency with dart pub add characters before running this standalone example. The algorithm allocates a cluster list and an output string, so its storage grows with input size. Grapheme-safe reversal is not a complete language-aware text transformation: bidirectional display and context-sensitive shaping can still make the visual result surprising. It also does not normalize canonically equivalent strings.

Dart example

import 'package:characters/characters.dart';

String reverseCharacters(String input) =>
    input.characters.toList().reversed.join();

void main() {
  const text = 'A\u0065\u0301๐Ÿ˜€'; // A, e + combining acute, emoji.
  print(reverseCharacters(text)); // ๐Ÿ˜€eฬA
  print(text.length); // 5 UTF-16 code units.
  print(text.runes.length); // 4 Unicode code points.
  print(text.characters.length); // 3 grapheme clusters.
}
import 'package:characters/characters.dart';

String reverseCharacters(String input) =>
    input.characters.toList().reversed.join();

void main() {
  const text = 'A\u0065\u0301๐Ÿ˜€'; // A, e + combining acute, emoji.
  print(reverseCharacters(text)); // ๐Ÿ˜€eฬA
  print(text.length); // 5 UTF-16 code units.
  print(text.runes.length); // 4 Unicode code points.
  print(text.characters.length); // 3 grapheme clusters.
}
import 'package:characters/characters.dart';

String reverseCharacters(String input) =>
    input.characters.toList().reversed.join();

void main() {
  const text = 'A\u0065\u0301๐Ÿ˜€'; // A, e + combining acute, emoji.
  print(reverseCharacters(text)); // ๐Ÿ˜€eฬA
  print(text.length); // 5 UTF-16 code units.
  print(text.runes.length); // 4 Unicode code points.
  print(text.characters.length); // 3 grapheme clusters.
}

107. Why must UTF-8 be decoded across chunks rather than decoded separately for every byte buffer?

Transport buffers are arbitrary byte chunks, not guaranteed character boundaries. A multi-byte UTF-8 sequence can begin in one chunk and finish in the next. Calling utf8.decode separately on each buffer can therefore throw for otherwise valid input, or introduce replacement characters if malformed input is allowed.

A stream decoder preserves partial sequence state between chunks and checks the final incomplete sequence when input ends. Decode bytes first, then apply text-level transformations such as line splitting; neither byte-buffer boundaries nor decoded-string events necessarily represent complete lines. Choose malformed-input behavior explicitly rather than silently accepting corrupted data. The example splits the three-byte euro sign across two events and obtains one correct string. Joining the whole stream is suitable here only because this demonstration's input is bounded.

Dart example

import 'dart:async';
import 'dart:convert';

Future<void> main() async {
  final bytes = Stream<List<int>>.fromIterable([
    [0xE2],
    [0x82, 0xAC, 0x0A],
  ]);
  final lines = bytes
      .transform(utf8.decoder)
      .transform(const LineSplitter());
  print(await lines.toList()); // [โ‚ฌ]
}
import 'dart:async';
import 'dart:convert';

Future<void> main() async {
  final bytes = Stream<List<int>>.fromIterable([
    [0xE2],
    [0x82, 0xAC, 0x0A],
  ]);
  final lines = bytes
      .transform(utf8.decoder)
      .transform(const LineSplitter());
  print(await lines.toList()); // [โ‚ฌ]
}
import 'dart:async';
import 'dart:convert';

Future<void> main() async {
  final bytes = Stream<List<int>>.fromIterable([
    [0xE2],
    [0x82, 0xAC, 0x0A],
  ]);
  final lines = bytes
      .transform(utf8.decoder)
      .transform(const LineSplitter());
  print(await lines.toList()); // [โ‚ฌ]
}

108. How do conditional imports keep native-only libraries out of web builds?

A runtime if cannot make an unsupported import disappear from a compilation unit. Conditional imports or exports select a platform implementation at compile time, keeping native-only libraries such as dart:io out of the selected web dependency graph.

All implementations should expose the same API, with an explicit fallback for unsupported environments. Use library-availability conditions such as dart.library.io and dart.library.js_interop, rather than guessing the platform from a user-agent string. The condition identifies compilation capabilities, not whether the user granted access to a resource. Test each selected implementation because one target's successful build does not validate the others. Save the following four blocks as separate files in one directory; native execution prints the operating-system name, while a web build prints web.

main.dart

Dart example

import 'platform_stub.dart'
    if (dart.library.io) 'platform_io.dart'
    if (dart.library.js_interop) 'platform_web.dart' as platform;

void main() => print(platform.label());
import 'platform_stub.dart'
    if (dart.library.io) 'platform_io.dart'
    if (dart.library.js_interop) 'platform_web.dart' as platform;

void main() => print(platform.label());
import 'platform_stub.dart'
    if (dart.library.io) 'platform_io.dart'
    if (dart.library.js_interop) 'platform_web.dart' as platform;

void main() => print(platform.label());

platform_stub.dart

Dart example

String label() => 'unsupported';
String label() => 'unsupported';
String label() => 'unsupported';

platform_io.dart

Dart example

import 'dart:io';

String label() => Platform.operatingSystem;
import 'dart:io';

String label() => Platform.operatingSystem;
import 'dart:io';

String label() => Platform.operatingSystem;

platform_web.dart

Dart example

String label() => 'web';
String label() => 'web';
String label() => 'web';

109. Why does modern JavaScript interop use static declarations and explicit conversions?

Modern interop declares the JavaScript surface using external members and dart:js_interop types. This gives the compiler a visible contract and supports both JavaScript and Wasm compilation strategies, where Dart and JavaScript values need not share the same runtime representation.

Explicit conversions such as toJS and toDart make the boundary visible. They are not universally free, and collection conversions can have backend-specific copying or wrapping behavior. Static declarations also do not validate an arbitrary JavaScript object's runtime shape: a wrong declaration can still fail when invoked. Avoid treating Dart is checks or casts as a portable JavaScript type-validation strategy. This web-target example binds the existing JSON.stringify function with an intentionally narrow array-of-strings input contract; it needs no custom JavaScript function.

Dart example

import 'dart:js_interop';

@JS('JSON.stringify')
external JSString stringifyStrings(JSArray<JSString> values);

void main() {
  final values = <JSString>

import 'dart:js_interop';

@JS('JSON.stringify')
external JSString stringifyStrings(JSArray<JSString> values);

void main() {
  final values = <JSString>

import 'dart:js_interop';

@JS('JSON.stringify')
external JSString stringifyStrings(JSArray<JSString> values);

void main() {
  final values = <JSString>

110. What ownership and ABI rules must a Dart FFI wrapper enforce?

An FFI wrapper must match the native ABI: integer width and signedness, pointer types, calling convention, struct layout/alignment, and platform-specific representations. A Dart int parameter does not by itself identify the C integer width. Generate bindings from authoritative headers where possible, then validate them on each supported architecture.

Ownership is separate from typing. Document whether a pointer is borrowed or owned, how long it stays valid, and which allocator or native release function must free it. Prevent double-free and use-after-free, keep buffers alive while native code retains them, and respect callback/thread restrictions. Prefer explicit close or try/finally for timely release; finalizers are fallback cleanup. The native-only example requires dart pub add ffi and demonstrates matching calloc allocation with calloc.free, not an external C library binding.

Dart example

import 'dart:ffi';
import 'package:ffi/ffi.dart';

void main() {
  final bytes = calloc<Uint8>(3);
  try {
    bytes[0] = 7;
    print(bytes.asTypedList(3)); // [7, 0, 0]
  } finally {
    calloc.free(bytes);
  }
  // Neither bytes nor a view of it may be used after free.
}
import 'dart:ffi';
import 'package:ffi/ffi.dart';

void main() {
  final bytes = calloc<Uint8>(3);
  try {
    bytes[0] = 7;
    print(bytes.asTypedList(3)); // [7, 0, 0]
  } finally {
    calloc.free(bytes);
  }
  // Neither bytes nor a view of it may be used after free.
}
import 'dart:ffi';
import 'package:ffi/ffi.dart';

void main() {
  final bytes = calloc<Uint8>(3);
  try {
    bytes[0] = 7;
    print(bytes.asTypedList(3)); // [7, 0, 0]
  } finally {
    calloc.free(bytes);
  }
  // Neither bytes nor a view of it may be used after free.
}

111. Why is adding a Duration not always the same as advancing a local calendar date?

A Duration(days: 1) means exactly 24 hours, not โ€œthe same local time tomorrow.โ€ Across a daylight-saving transition, a local calendar day can contain a different number of elapsed hours. Adding a duration can therefore change the displayed hour or even miss the intended calendar date.

For calendar intent, construct the next local date from calendar components and define how ambiguous or nonexistent wall-clock times are handled. Dart's built-in DateTime represents UTC or the machine's local zone, not an arbitrary named time-zone rule set. Use a suitable zone-aware abstraction when a business rule names a specific region, and preserve date-only values as date-only data. The helper below preserves requested local components, but it is not a universal daylight-saving ambiguity policy.

Dart example

DateTime nextLocalDay(DateTime value) {
  if (value.isUtc) throw ArgumentError('Expected local time');
  return DateTime(value.year, value.month, value.day + 1,
      value.hour, value.minute, value.second,
      value.millisecond, value.microsecond);
}

void main() {
  final next = nextLocalDay(DateTime(2026, 10, 31, 12));
  print('${next.year}-${next.month}-${next.day}'); // 2026-11-1
}
DateTime nextLocalDay(DateTime value) {
  if (value.isUtc) throw ArgumentError('Expected local time');
  return DateTime(value.year, value.month, value.day + 1,
      value.hour, value.minute, value.second,
      value.millisecond, value.microsecond);
}

void main() {
  final next = nextLocalDay(DateTime(2026, 10, 31, 12));
  print('${next.year}-${next.month}-${next.day}'); // 2026-11-1
}
DateTime nextLocalDay(DateTime value) {
  if (value.isUtc) throw ArgumentError('Expected local time');
  return DateTime(value.year, value.month, value.day + 1,
      value.hour, value.minute, value.second,
      value.millisecond, value.microsecond);
}

void main() {
  final next = nextLocalDay(DateTime(2026, 10, 31, 12));
  print('${next.year}-${next.month}-${next.day}'); // 2026-11-1
}

112. How do you validate untrusted paths and URLs without confusing parsing with authorization?

Successful parsing establishes structure, not permission. A parsed URI can still target an internal service, use an unwanted scheme, embed credentials, or redirect to a forbidden destination. Apply an explicit scheme, host, port, and resource policy; recheck redirects and address resolution where server-side request forgery is a concern. Disabling automatic redirects helps enforce a deliberate redirect policy but is not a complete defense.

For files, reject unsupported path forms and compare resolved path components against an authorized root. A string prefix is insufficient: /safe-data-extra is not inside /safe-data. Symbolic links and filesystem changes between checking and opening also matter. Resolving links requires an existing object and does not eliminate check/use races. Strong isolation may require operating-system permissions or sandboxed file access. Test traversal, alternate separators, symlinks, redirects, and authorization failures separately from parser tests.

113. How would you parse a compact key-value format with explicit validation and error locations?

Define the grammar before splitting text. This example accepts semicolon-separated key=value pairs, ASCII identifier keys, and values containing neither ; nor =. Empty input and empty values are allowed; duplicate keys, trailing separators, malformed keys, and extra equals signs are rejected. There is no escaping or implicit whitespace trimming.

Errors carry the original source and a zero-based UTF-16 code-unit offset, matching Dart string indexing rather than user-perceived character positions. Each segment is scanned a bounded number of times, giving O(n) parsing work plus output storage under ordinary map hashing assumptions. A caller should impose an input-size limit before parsing untrusted data. If requirements add quoting, escapes, or nested structures, extend the grammar deliberately rather than accumulating ambiguous split-and-replace rules.

Dart example

Map<String, String> parsePairs(String source) {
  final result = <String, String>{};
  final keyPattern = RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$');
  var start = 0;
  while (start < source.length) {
    final separator = source.indexOf(';', start);
    final end = separator < 0 ? source.length : separator;
    final segment = source.substring(start, end);
    final equals = segment.indexOf('=');
    if (equals <= 0) {
      throw FormatException('Expected key=value', source, start);
    }
    final key = segment.substring(0, equals);
    final keyMatch = keyPattern.firstMatch(key);
    if (keyMatch == null || keyMatch.end != key.length) {
      throw FormatException('Invalid key', source, start);
    }
    final extra = segment.indexOf('=', equals + 1);
    if (extra >= 0) {
      throw FormatException('Extra equals sign', source, start + extra);
    }
    if (result.containsKey(key)) {
      throw FormatException('Duplicate key', source, start);
    }
    result[key] = segment.substring(equals + 1);
    if (separator < 0) break;
    start = end + 1;
    if (start == source.length) {
      throw FormatException('Trailing separator', source, end);
    }
  }
  return result;
}

void main() {
  print(parsePairs('mode=fast;note=')); // {mode: fast, note: }
  try {
    parsePairs('a=1;a=2');
  } on FormatException catch (error) {
    print(error.offset); // 4
  }
}
Map<String, String> parsePairs(String source) {
  final result = <String, String>{};
  final keyPattern = RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$');
  var start = 0;
  while (start < source.length) {
    final separator = source.indexOf(';', start);
    final end = separator < 0 ? source.length : separator;
    final segment = source.substring(start, end);
    final equals = segment.indexOf('=');
    if (equals <= 0) {
      throw FormatException('Expected key=value', source, start);
    }
    final key = segment.substring(0, equals);
    final keyMatch = keyPattern.firstMatch(key);
    if (keyMatch == null || keyMatch.end != key.length) {
      throw FormatException('Invalid key', source, start);
    }
    final extra = segment.indexOf('=', equals + 1);
    if (extra >= 0) {
      throw FormatException('Extra equals sign', source, start + extra);
    }
    if (result.containsKey(key)) {
      throw FormatException('Duplicate key', source, start);
    }
    result[key] = segment.substring(equals + 1);
    if (separator < 0) break;
    start = end + 1;
    if (start == source.length) {
      throw FormatException('Trailing separator', source, end);
    }
  }
  return result;
}

void main() {
  print(parsePairs('mode=fast;note=')); // {mode: fast, note: }
  try {
    parsePairs('a=1;a=2');
  } on FormatException catch (error) {
    print(error.offset); // 4
  }
}
Map<String, String> parsePairs(String source) {
  final result = <String, String>{};
  final keyPattern = RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$');
  var start = 0;
  while (start < source.length) {
    final separator = source.indexOf(';', start);
    final end = separator < 0 ? source.length : separator;
    final segment = source.substring(start, end);
    final equals = segment.indexOf('=');
    if (equals <= 0) {
      throw FormatException('Expected key=value', source, start);
    }
    final key = segment.substring(0, equals);
    final keyMatch = keyPattern.firstMatch(key);
    if (keyMatch == null || keyMatch.end != key.length) {
      throw FormatException('Invalid key', source, start);
    }
    final extra = segment.indexOf('=', equals + 1);
    if (extra >= 0) {
      throw FormatException('Extra equals sign', source, start + extra);
    }
    if (result.containsKey(key)) {
      throw FormatException('Duplicate key', source, start);
    }
    result[key] = segment.substring(equals + 1);
    if (separator < 0) break;
    start = end + 1;
    if (start == source.length) {
      throw FormatException('Trailing separator', source, end);
    }
  }
  return result;
}

void main() {
  print(parsePairs('mode=fast;note=')); // {mode: fast, note: }
  try {
    parsePairs('a=1;a=2');
  } on FormatException catch (error) {
    print(error.offset); // 4
  }
}

114. How would you implement a capacity-bounded least-recently-used cache?

An LRU cache evicts the entry that has gone longest without a successful access. An insertion-ordered LinkedHashMap can represent that order: remove and reinsert a hit to make it newest, and evict the first key after exceeding capacity. Updating an existing key's value alone does not move it.

This version rejects negative capacity, treats zero as disabled caching, and deliberately prohibits null values so a null lookup unambiguously means a miss. Reads and writes have expected constant-time map cost for well-behaved hashes; retained entries are bounded by capacity. Stable key equality is essential. This is a count limit, not a byte-memory limit, and it provides neither time-to-live expiry nor cross-isolate sharing. Large values may need a separate weighted eviction policy.

Dart example

import 'dart:collection';

class Lru<K extends Object, V extends Object> {
  final int capacity;
  final _items = LinkedHashMap<K, V>();
  Lru(this.capacity) {
    if (capacity < 0) throw ArgumentError.value(capacity);
  }
  V? get(K key) {
    final value = _items.remove(key);
    if (value != null) _items[key] = value;
    return value;
  }
  void put(K key, V value) {
    if (capacity == 0) return;
    _items.remove(key);
    _items[key] = value;
    if (_items.length > capacity) _items.remove(_items.keys.first);
  }
}

void main() {
  final cache = Lru<String, int>(2);
  cache.put('a', 1);
  cache.put('b', 2);
  print(cache.get('a')); // 1: a becomes newest.
  cache.put('c', 3);
  print(cache.get('b')); // null: b was evicted.
}
import 'dart:collection';

class Lru<K extends Object, V extends Object> {
  final int capacity;
  final _items = LinkedHashMap<K, V>();
  Lru(this.capacity) {
    if (capacity < 0) throw ArgumentError.value(capacity);
  }
  V? get(K key) {
    final value = _items.remove(key);
    if (value != null) _items[key] = value;
    return value;
  }
  void put(K key, V value) {
    if (capacity == 0) return;
    _items.remove(key);
    _items[key] = value;
    if (_items.length > capacity) _items.remove(_items.keys.first);
  }
}

void main() {
  final cache = Lru<String, int>(2);
  cache.put('a', 1);
  cache.put('b', 2);
  print(cache.get('a')); // 1: a becomes newest.
  cache.put('c', 3);
  print(cache.get('b')); // null: b was evicted.
}
import 'dart:collection';

class Lru<K extends Object, V extends Object> {
  final int capacity;
  final _items = LinkedHashMap<K, V>();
  Lru(this.capacity) {
    if (capacity < 0) throw ArgumentError.value(capacity);
  }
  V? get(K key) {
    final value = _items.remove(key);
    if (value != null) _items[key] = value;
    return value;
  }
  void put(K key, V value) {
    if (capacity == 0) return;
    _items.remove(key);
    _items[key] = value;
    if (_items.length > capacity) _items.remove(_items.keys.first);
  }
}

void main() {
  final cache = Lru<String, int>(2);
  cache.put('a', 1);
  cache.put('b', 2);
  print(cache.get('a')); // 1: a becomes newest.
  cache.put('c', 3);
  print(cache.get('b')); // null: b was evicted.
}

115. How would you deduplicate in-flight asynchronous loads without caching failures forever?

Store the future representing an active load, not just its eventual value. Concurrent callers for the same key then receive the same completion. Remove the entry when it settles so failures do not poison all future attempts; this example also removes successes because it coalesces in-flight work rather than maintaining a completed-value cache.

The loader is scheduled through Future, so it runs after the shared future has been installed and synchronous throws become future errors. The cleanup future returned by whenComplete is the one callers receive, avoiding an unobserved failing cleanup branch. Identity checking prevents an older completion from removing a newer request after invalidation. Invalidation does not abort the old operation. Callers still own error handling, and one caller's cancellation should not silently cancel work needed by other callers.

Dart example

import 'dart:async';

class InFlight<K extends Object, V> {
  final Future<V> Function(K) _load;
  final _pending = <K, Future<V>>{};
  InFlight(this._load);

  Future<V> get(K key) {
    final existing = _pending[key];
    if (existing != null) return existing;
    late final Future<V> shared;
    shared = Future<V>(() => _load(key)).whenComplete(() {
      if (identical(_pending[key], shared)) _pending.remove(key);
    });
    _pending[key] = shared;
    return shared;
  }
  void invalidate(K key) => _pending.remove(key);
}

Future<void> main() async {
  var calls = 0;
  final loads = InFlight<String, int>((key) async => ++calls);
  final first = loads.get('a');
  final second = loads.get('a');
  print(identical(first, second)); // true
  print(await first); // 1
  await second;
  print(await loads.get('a')); // 2: completed loads are not cached.
}
import 'dart:async';

class InFlight<K extends Object, V> {
  final Future<V> Function(K) _load;
  final _pending = <K, Future<V>>{};
  InFlight(this._load);

  Future<V> get(K key) {
    final existing = _pending[key];
    if (existing != null) return existing;
    late final Future<V> shared;
    shared = Future<V>(() => _load(key)).whenComplete(() {
      if (identical(_pending[key], shared)) _pending.remove(key);
    });
    _pending[key] = shared;
    return shared;
  }
  void invalidate(K key) => _pending.remove(key);
}

Future<void> main() async {
  var calls = 0;
  final loads = InFlight<String, int>((key) async => ++calls);
  final first = loads.get('a');
  final second = loads.get('a');
  print(identical(first, second)); // true
  print(await first); // 1
  await second;
  print(await loads.get('a')); // 2: completed loads are not cached.
}
import 'dart:async';

class InFlight<K extends Object, V> {
  final Future<V> Function(K) _load;
  final _pending = <K, Future<V>>{};
  InFlight(this._load);

  Future<V> get(K key) {
    final existing = _pending[key];
    if (existing != null) return existing;
    late final Future<V> shared;
    shared = Future<V>(() => _load(key)).whenComplete(() {
      if (identical(_pending[key], shared)) _pending.remove(key);
    });
    _pending[key] = shared;
    return shared;
  }
  void invalidate(K key) => _pending.remove(key);
}

Future<void> main() async {
  var calls = 0;
  final loads = InFlight<String, int>((key) async => ++calls);
  final first = loads.get('a');
  final second = loads.get('a');
  print(identical(first, second)); // true
  print(await first); // 1
  await second;
  print(await loads.get('a')); // 2: completed loads are not cached.
}

116. How do you design an immutable model that does not leak mutable collection state?

A final field prevents rebinding; it does not freeze the object referenced by that field. Copy incoming collections and expose an unmodifiable result when the model owns a stable snapshot. An UnmodifiableListView blocks writes through the view but still reflects changes to its backing collection, so it is insufficient when callers retain that mutable backing list.

Immutability is also shallow unless the elements are immutable or copied recursively. This model contains strings, so an unmodifiable snapshot is sufficient. It defines sequence-based equality and a matching hash instead of relying on ordinary lists' identity equality. The final class blocks external-library subtypes; same-library subclasses must still respect that equality contract. Large collection models should consider the O(n) construction, equality, and hash costs rather than assume immutability makes every operation constant time.

Dart example

final class Labels {
  final List<String> values;
  Labels(Iterable<String> values)
      : values = List<String>.unmodifiable(values);

  @override
  bool operator ==(Object other) {
    if (other is! Labels || values.length != other.values.length) {
      return false;
    }
    for (var i = 0; i < values.length; i++) {
      if (values[i] != other.values[i]) return false;
    }
    return true;
  }
  @override
  int get hashCode => Object.hashAll(values);
}

void main() {
  final 

final class Labels {
  final List<String> values;
  Labels(Iterable<String> values)
      : values = List<String>.unmodifiable(values);

  @override
  bool operator ==(Object other) {
    if (other is! Labels || values.length != other.values.length) {
      return false;
    }
    for (var i = 0; i < values.length; i++) {
      if (values[i] != other.values[i]) return false;
    }
    return true;
  }
  @override
  int get hashCode => Object.hashAll(values);
}

void main() {
  final 

final class Labels {
  final List<String> values;
  Labels(Iterable<String> values)
      : values = List<String>.unmodifiable(values);

  @override
  bool operator ==(Object other) {
    if (other is! Labels || values.length != other.values.length) {
      return false;
    }
    for (var i = 0; i < values.length; i++) {
      if (values[i] != other.values[i]) return false;
    }
    return true;
  }
  @override
  int get hashCode => Object.hashAll(values);
}

void main() {
  final 

117. How do a package's SDK lower bound and language version affect new Dart syntax?

A package's SDK constraint controls which SDK versions may resolve it, and its lower bound determines the default language version used for its Dart libraries. Installing a newer SDK does not automatically opt a package with an older language version into every new syntax feature. A file-level language-version comment can also keep a library on an older supported version.

Raise the lower bound when the package genuinely requires newer syntax or APIs, then test that oldest supported SDK as well as the current supported release. An upper bound is not a substitute for compatibility testing. The minimal pubspec below deliberately targets the Dart 3.13 family and later compatible 3.x SDKs. It is a package constraint example, not a claim that every dependency supports every SDK in the range.

YAML example

name: interview_sample
environment:
  sdk: '>=3.13.0 <4.0.0'
name: interview_sample
environment:
  sdk: '>=3.13.0 <4.0.0'
name: interview_sample
environment:
  sdk: '>=3.13.0 <4.0.0'

118. How do you make isolate and asynchronous tests deterministic and ensure cleanup?

Synchronize tests on observable events: a completer, a reply, a stream expectation, or a protocol acknowledgment. Sleeping for an estimated amount of time makes tests depend on scheduler and machine speed. Inject clocks and retry-delay strategies when testing time-dependent policies; a timeout should detect a stalled test, not serve as its synchronization mechanism.

Return or await every asynchronous expectation so the runner owns failures. Register cleanup before starting work, then close ports, cancel subscriptions, and terminate any worker that could outlive the test. Test failure, cancellation, and unexpected-exit paths as well as success. Add test with dart pub add --dev test, save this native-only example as test/worker_test.dart, and run dart test. Its timeout is only a deadlock guard; the worker reply determines success.

Dart example

import 'dart:async';
import 'dart:isolate';
import 'package:test/test.dart';

void reply(SendPort parent) => parent.send(42);

void main() {
  test('worker replies without a timing sleep', () async {
    final inbox = ReceivePort();
    Isolate? worker;
    addTearDown(() {
      worker?.kill(priority: Isolate.immediate);
      inbox.close();
    });
    final response = inbox.first;
    worker = await Isolate.spawn(reply, inbox.sendPort);
    expect(await response.timeout(const Duration(seconds: 5)), 42);
  }, testOn: 'vm');

  test('future error is observed before completion', () async {
    final result = Completer<int>();
    final checked = expectLater(result.future, throwsStateError);
    result.completeError(StateError('expected failure'));
    await checked;
  });
}
import 'dart:async';
import 'dart:isolate';
import 'package:test/test.dart';

void reply(SendPort parent) => parent.send(42);

void main() {
  test('worker replies without a timing sleep', () async {
    final inbox = ReceivePort();
    Isolate? worker;
    addTearDown(() {
      worker?.kill(priority: Isolate.immediate);
      inbox.close();
    });
    final response = inbox.first;
    worker = await Isolate.spawn(reply, inbox.sendPort);
    expect(await response.timeout(const Duration(seconds: 5)), 42);
  }, testOn: 'vm');

  test('future error is observed before completion', () async {
    final result = Completer<int>();
    final checked = expectLater(result.future, throwsStateError);
    result.completeError(StateError('expected failure'));
    await checked;
  });
}
import 'dart:async';
import 'dart:isolate';
import 'package:test/test.dart';

void reply(SendPort parent) => parent.send(42);

void main() {
  test('worker replies without a timing sleep', () async {
    final inbox = ReceivePort();
    Isolate? worker;
    addTearDown(() {
      worker?.kill(priority: Isolate.immediate);
      inbox.close();
    });
    final response = inbox.first;
    worker = await Isolate.spawn(reply, inbox.sendPort);
    expect(await response.timeout(const Duration(seconds: 5)), 42);
  }, testOn: 'vm');

  test('future error is observed before completion', () async {
    final result = Completer<int>();
    final checked = expectLater(result.future, throwsStateError);
    result.completeError(StateError('expected failure'));
    await checked;
  });
}

119. How do you design a reproducible microbenchmark and avoid unsupported performance claims?

A reproducible benchmark identifies the SDK, backend, build flags, hardware, input distribution, and measured unit. Keep setup outside the timed region unless setup is the question. Separate warm-up from samples, consume results, run multiple samples and processes, and report variability rather than one attractive minimum. Check a profile to confirm the compiler has not eliminated or transformed away the intended work.

The example prints raw microsecond samples and an observable checksum. It is a small measurement harness, not evidence that this algorithm is fast or that JIT results predict AOT performance. Compare implementations on identical data, validate correctness independently, and include allocation or end-to-end latency when relevant. Do not publish a percentage improvement without measurements from the stated target. No timing output is prescribed because it depends on the environment.

Dart example

int checksum(List<int> values) {
  var result = 0;
  for (final value in values) {
    result = (result + value * value) & 0x3fffffff;
  }
  return result;
}

void main() {
  final input = List<int>.generate(10000, (i) => i % 97);
  var sink = 0;
  for (var i = 0; i < 20; i++) {
    sink = (sink + checksum(input)) & 0x3fffffff;
  }
  final samples = <int>[];
  for (var sample = 0; sample < 10; sample++) {
    final watch = Stopwatch()..start();
    for (var repeat = 0; repeat < 100; repeat++) {
      sink = (sink + checksum(input)) & 0x3fffffff