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.
What is Dart, and how do its native and web targets differ?
How do you write a Dart entry point and read command-line arguments?
How does var differ from an explicitly typed variable and dynamic?
What is the difference between final and const?
Which built-in value and collection types does Dart provide?
How do you parse and convert numbers safely in Dart?
What does sound null safety guarantee in Dart?
How do the null-aware operators differ from the non-null assertion operator?
What does late do, and when can it fail?
When should you use is, is!, and as?
How do division, truncating division, and remainder work in Dart?
How do interpolation, raw strings, and multiline strings work?
Does String.length count user-perceived characters?
How do growable, fixed-length, and unmodifiable lists differ?
How do you choose between a List, Set, and Map?
Why can a map lookup return null even when its value type is non-nullable?
How do collection if, collection for, and spread elements work?
When should you use for, for-in, while, break, and continue?
How does a switch expression differ from a switch statement?
How do you declare a function and use arrow syntax?
How do named, required, optional positional, and default parameters work?
How do first-class functions and closures work in Dart?
How do classes, fields, and instance methods work?
What are unnamed constructors, named constructors, and initializer lists?
How do initializing formals and super parameters reduce constructor boilerplate?
How do static members differ from instance members?
How do inheritance and method overriding work?
How does implementing an interface differ from extending an abstract class?
What problem does a mixin solve?
When are getters and setters useful?
What can an enum contain beyond named constants?
How do generic classes and functions improve type safety?
How do import prefixes, show, and hide control library names?
What does an underscore make private in Dart?
Why are assertions not a substitute for validating external input?
How do on, catch, rethrow, and finally handle failures?
What is a Future, and what do async and await change?
How is a Stream different from a Future, and how does await for consume it?
What do pubspec.yaml, dart pub get, dart analyze, and dart format do?
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.
When should initialization use a constructor, a nullable field, or late final?
How do const constructors affect identity and immutability?
When should you use a factory or redirecting constructor?
How do you implement value equality and a consistent hashCode?
Why is copying a collection not necessarily a deep copy?
How do reified generic types and covariant collections affect runtime checks?
How do generic bounds constrain a reusable API?
When are Iterable transformations lazy, and when are they evaluated?
How do you sort objects with a comparator without relying on a stable sort?
How do fold and reduce behave on empty collections?
How does an unmodifiable snapshot differ from an unmodifiable view?
How are extension methods resolved when static and runtime types differ?
How does an extension type differ from an extension method and a wrapper class?
What do base, interface, final, and sealed restrict across library boundaries?
How can a sealed hierarchy model success and failure exhaustively?
What defines a record's shape, type, and equality?
How do list, map, and object patterns validate and destructure data?
When should you use if-case patterns and when guards?
How do a mixin's on constraint, super calls, and application order interact?
How do typedefs, constructor tear-offs, and callable objects simplify APIs?
How do you validate decoded JSON before constructing a typed model?
How do you serialize a Dart model without assuming every object is JSON-compatible?
How do sync*, async*, yield, and yield* differ?
What order do synchronous code, microtasks, and event-queue tasks run in?
How do you start independent asynchronous operations concurrently and preserve result order?
What do Future.wait's eagerError and cleanUp options actually guarantee?
When does try/catch require return await to intercept a Future failure?
Does Future.timeout cancel the underlying operation?
How do single-subscription and broadcast streams differ?
How do map and asyncMap differ when processing a stream?
Who owns a StreamSubscription, and how should it be paused and canceled?
How do you create and close a StreamController without losing lifecycle control?
How do you read a large text file incrementally on native Dart?
How do you close native file handles reliably when an operation fails?
How do you construct request URIs, handle HTTP status codes, and close an owned client?
How do you write tests for Futures, errors, and streams?
How do dependencies, dev_dependencies, SDK constraints, and lockfiles fit together?
How do analyzer settings and lints enforce stricter typing?
How would you remove duplicates while preserving first-seen order?
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.
How do Object, Object?, dynamic, void, and Never differ in API design?
Why can type promotion fail for fields or captured variables?
How do function subtyping and covariant parameters affect substitutability?
When are self-referential generic bounds useful, and what do they not guarantee?
How do class modifiers change the compatibility promises of a public package?
Why is an extension type not a runtime security or validation boundary?
How do exhaustiveness, guarded patterns, and unreachable cases interact?
How do Future(), Future.microtask(), and Future.sync() schedule work and capture errors?
What can zones intercept, and why can asynchronous errors fail to cross error-zone boundaries?
How do you adapt a callback API with Completer while preventing double completion?
How do you design cooperative cancellation when Future itself has no cancel method?
How would you implement bounded asynchronous concurrency while preserving input order?
How do stream pause, buffering, and cancellation affect backpressure?
How do you design retries with backoff without hiding permanent errors or duplicating side effects?
How can overlapping asynchronous requests produce stale results on a single isolate?
When should CPU-bound work use Isolate.run, and what changes on the web?
Which objects can cross isolate boundaries, and why can captured closures be a problem?
How do you structure a long-lived isolate's request-response protocol and shutdown?
What does TransferableTypedData transfer, and what happens to ownership afterward?
How should a parent isolate observe worker failures and unexpected exits?
How do you profile Dart code without confusing JIT warm-up with AOT performance?
How can a garbage-collected Dart program still retain memory unnecessarily?
How do collection choice and equality behavior affect algorithmic cost?
How do integer precision and bitwise behavior differ between native and JavaScript targets?
What pitfalls arise with floating-point equality, NaN, infinity, and monetary values?
How would you reverse user-perceived characters without splitting surrogate pairs or combining sequences?
Why must UTF-8 be decoded across chunks rather than decoded separately for every byte buffer?
How do conditional imports keep native-only libraries out of web builds?
Why does modern JavaScript interop use static declarations and explicit conversions?
What ownership and ABI rules must a Dart FFI wrapper enforce?
Why is adding a Duration not always the same as advancing a local calendar date?
How do you validate untrusted paths and URLs without confusing parsing with authorization?
How would you parse a compact key-value format with explicit validation and error locations?
How would you implement a capacity-bounded least-recently-used cache?
How would you deduplicate in-flight asynchronous loads without caching failures forever?
How do you design an immutable model that does not leak mutable collection state?
How do a package's SDK lower bound and language version affect new Dart syntax?
How do you make isolate and asynchronous tests deterministic and ensure cleanup?
How do you design a reproducible microbenchmark and avoid unsupported performance claims?
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Shell command
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 |
|---|---|---|
| Yes, with required subtype modifier | No |
| No | Yes |
| No | No |
| No | No |
The two-file example permits inheritance but rejects external implementation. Restrictions are per library, not simply per directory.
Dart example
Dart example
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 |
|---|---|
| Clients may implement, but not extend, the class. |
| Clients may extend, but not implement; subtypes preserve the restriction. |
| Clients cannot extend or implement it. |
| 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
platform_stub.dart
Dart example
platform_io.dart
Dart example
platform_web.dart
Dart example
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
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
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
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
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
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
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
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
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
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
