Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 61 ยท Practice and Review

Dart Interview Questions

30 Dart interview questions with concise answers on null safety, const vs final, mixins, class modifiers, futures, streams, the event loop, isolates and compilation.

Dart interviews, whether for a Flutter role or a server-side one, check two things: do you know how the language behaves, and can you explain it clearly? This page collects 30 questions that come up again and again, grouped by topic, with short and accurate answers. The code samples are real Dart and are read-only on this site; two small TypeScript stand-ins at the end let you run the ideas that have a close equivalent.

Answer each question out loud before you open it. If you cannot explain an idea in two or three sentences, follow the link to its lesson. In a real interview, a correct short answer with a tiny example beats a long recital, and mentioning a trade-off ("this is safer, but costs one extra check") shows experience.

Tip: many answers have a "gotcha" that interviewers like to probe, such as "a final list can still be modified" or "a timeout does not cancel a future". Look for those in the answers below.

Language basics

1. What is Dart, and where does it run?

Dart is a statically typed, garbage-collected, object-oriented language from Google. It is best known as the language of Flutter, but it also runs command-line tools and servers on the Dart VM or as native executables, and in browsers after compiling to JavaScript or WebAssembly. One language for the app and the backend is a common selling point. See What Is Dart?.

2. What is the difference between var, final and const?

var declares a variable whose type is inferred and which can be reassigned. final means "assigned exactly once", and the value may be computed at runtime. const means a compile-time constant: the value must be known when the program is compiled. A const variable is implicitly final.

The gotcha: final list = [1, 2] cannot be reassigned, but list.add(3) works because the list itself is mutable. const list = [1, 2] creates a deeply immutable list, and add throws at runtime. See Variables, var, final and const.

3. What is sound null safety?

Types are non-nullable by default: String can never hold null, while String? can. The compiler tracks this and rejects code that might dereference null, and because the guarantee is sound, the runtime can rely on it (no hidden null checks, better optimization). The classic NullPointerException becomes a compile-time error in most cases. See Null Safety.

4. Explain ?., ??, ??= and !.
  • a?.b returns null if a is null, otherwise a.b.
  • a ?? b returns a unless it is null, then b.
  • a ??= b assigns b only when a is currently null.
  • a! asserts that a is not null; if you are wrong, it throws at runtime.

Prefer a null check (which promotes the type for local variables) over !, and treat every ! as a small risk.

5. What does the late keyword do?

late promises the compiler that a non-nullable variable will be assigned before it is read, so it does not need an initial value. If you read it too early, Dart throws a LateInitializationError. With an initializer (late final x = compute();) the expression runs lazily on the first read, which is a neat way to defer expensive work. See late Variables.

6. What is the difference between dynamic, Object and Object??

Object? is the top type: every value, including null, fits, but you may only call methods that every object has. Object is the same without null. dynamic turns static checking off: any member access compiles, and mistakes surface only at runtime. Use Object? when you mean "anything" and cast or test the type before use. See The Type System.

7. How do / and ~/ differ?

/ always returns a double (7 / 2 is 3.5). ~/ is truncating integer division and returns an int (7 ~/ 2 is 3). % gives the remainder, and for negative numbers the result of % in Dart is never negative (-7 % 3 is 2), while remainder keeps the sign. See Numbers.

8. How are named, optional positional and required parameters declared?
DART
void connect(String host, [int port = 80]) {}            // optional positional
void send({required String to, String? cc, int retries = 3}) {} // named

Named parameters are optional unless marked required or non-nullable without a default. At the call site, send(to: '[email protected]', retries: 5) is readable and order-independent. See Parameters.

9. What are records and patterns?

A record is an anonymous, immutable aggregate such as (String, int) or ({int x, int y}). It is perfect for returning several values. Patterns match a value's shape and bind variables: final (name, age) = person;, case {'id': int id}, and switch cases. Records have structural equality: (1, 2) == (1, 2) is true. See Records and Patterns.

10. What is the cascade operator?

.. calls a method or sets a field on the same object and then yields that object, so you can chain several operations: StringBuffer()..write('a')..write('b'). ?.. is the null-aware form. It replaces repetitive variable. prefixes when configuring an object.

Classes and object-oriented Dart

11. Does Dart have interfaces?

There is no separate interface declaration for ordinary use: every class defines an implicit interface. You can write class Fake implements Service, and then you must implement every public member and inherit no code. Since Dart 3, the interface class modifier makes the intent explicit, and outside its library such a class may be implemented but not extended. See Abstract Classes and Implicit Interfaces.

12. What is the difference between extends, implements and with?

extends inherits code from one superclass (single inheritance). implements promises to supply the whole interface of one or more types and inherits nothing. with mixes in the code of one or more mixins. A class can use all three: class Dog extends Animal with Swimmer implements Comparable<Dog>.

13. What is a mixin, and what does on do?

A mixin is a bundle of fields and methods that can be added to a class hierarchy with with, reusing code without inheritance. mixin Logger on Service restricts the mixin so it can only be applied to classes that extend or implement Service, which lets the mixin call Service members. If several mixins define the same member, the last one listed wins (linearization). See Mixins.

14. Name the kinds of constructors.
  • Generative: the normal kind, Point(this.x, this.y);.
  • Named: Point.origin() : x = 0, y = 0;.
  • Redirecting: Point.unit() : this(1, 1);.
  • Const: const Point(this.x, this.y);, only for classes with all-final fields.
  • Factory: factory Point.fromJson(...), may return an existing or a different instance because it does not allocate by itself.

The initializer list (after the colon) runs before the constructor body and is the place to set final fields and assert invariants. See Constructors.

15. Which class modifiers did Dart 3 add?

sealed (a closed family of subtypes in one library, enabling exhaustive switch; cannot be instantiated), final (cannot be extended or implemented outside its library), base (can be extended but not implemented, so the constructor and members are always inherited), interface (can be implemented but not extended outside the library) and mixin class. They let library authors control how their types are used. See Class Modifiers.

16. How do you make two objects equal by value?

Override operator == and hashCode together, so equal objects have equal hashes. Object.hash(a, b) combines fields. Alternatively use records, which have value equality built in. Without the override, == compares identity. See Operator Overloading.

17. How does privacy work in Dart?

A leading underscore (_balance) makes a member private to its library, which is usually the file, not the class. Other code in the same file can still access it. There are no public, private or protected keywords. See Classes and Objects.

18. What are enhanced enums and extension methods?

Enhanced enums can have fields, a const constructor, methods and can implement interfaces. Extension methods add members to an existing type without changing or subclassing it (extension on String { bool get isBlank => trim().isEmpty; }). They are resolved statically, so they do not work on dynamic receivers. Extension types (Dart 3.3) wrap a value with a zero-cost, different interface. See Enums and Extension Methods.

19. Are Dart generics reified?

Yes. Unlike Java's type erasure, the type arguments exist at runtime: <int>[] is List<String> is false and list.runtimeType prints List<int>. This also means is List<int> checks work. See Generics.

20. What does const canonicalization mean?

Equal const instances are the same object in memory: identical(const Point(1, 2), const Point(1, 2)) is true. Constants cost no allocation at run time, which is why Flutter encourages const widgets.

Errors and asynchrony

21. What is the difference between Exception and Error?

An Exception models a foreseeable, recoverable condition (a FormatException, a failed network call) and is meant to be caught. An Error signals a programming bug (StateError, ArgumentError, RangeError, TypeError) and normally should not be caught: fix the code instead. You can throw any object in Dart, but you should throw one of these. See Exceptions.

22. What is a Future, and how does async/await work?

A Future<T> represents a value (or error) that will be available later. An async function always returns a Future, and await pauses that function (not the thread) until the future completes, letting other work run in the meantime. Errors from an awaited future are thrown at the await, so ordinary try/catch works. See Futures.

23. When would you use Future.wait?

To run independent futures concurrently and wait for all of them: final [a, b] = await Future.wait([fetchA(), fetchB()]);. The total time is that of the slowest future. If one fails, the combined future fails (with eagerError: true it fails at the first error). Do not use it for dependent calls.

24. Future versus Stream, and single-subscription versus broadcast?

A Future delivers one result; a Stream delivers zero or more events over time and then closes. A normal stream can have one listener (a second listen throws a StateError) and buffers events until someone listens. A broadcast stream allows many listeners but delivers events only to those subscribed at that moment. async* and yield create streams; await for consumes them. See Streams.

25. Explain the event loop and the microtask queue.

Each isolate is single-threaded and runs an event loop with two queues. After the current synchronous code, all microtasks run (futures' .then continuations and scheduleMicrotask), then the loop takes one event (timers, I/O, Future(...)), drains microtasks again, and repeats. A long synchronous computation blocks everything, including the UI. See The Event Loop.

flowchart TD
    A["Run synchronous code"] --> B{"Microtasks<br/>waiting?"}
    B -->|"yes"| C["Run all microtasks"]
    C --> B
    B -->|"no"| D{"Events<br/>waiting?"}
    D -->|"yes"| E["Run one event"]
    E --> B
    D -->|"no"| F["Wait for new events"]
    F --> D

The loop always empties the microtask queue before it takes the next event.

26. Does a timeout cancel a Future?

No. future.timeout(...) only stops waiting: the caller gets a TimeoutException (or the onTimeout result) while the original work continues and its result is discarded. Dart futures have no cancel operation. For cancellable work, use a StreamSubscription, a package such as async's CancelableOperation, or design the work to check a flag.

27. What are isolates, and why does Dart have them?

An isolate is an independent worker with its own memory heap and event loop. Isolates share no memory, so there are no data races or locks; they communicate by sending messages over ports. Isolate.run(() => heavyWork()) runs a function in a new isolate and returns its result as a Future, which keeps a Flutter UI smooth during CPU-heavy tasks. On the web, isolates are not available and web workers are used instead. See Isolates.

flowchart LR
    A["Main isolate<br/>own heap"] -->|"message (copied)"| B["Worker isolate<br/>own heap"]
    B -->|"result message"| A

Isolates never share memory; they exchange messages.

28. Does Dart support multithreading?

Not with shared-memory threads. Concurrency (many tasks interleaved on one thread) uses futures and streams; parallelism (several CPU cores) uses isolates. Futures for I/O do not need extra threads because the operating system waits for the I/O, not your code.

Tooling and performance

29. How is Dart compiled and run?

During development the Dart VM uses JIT compilation, which enables fast startup and stateful hot reload. For release, AOT compilation produces a native executable (dart compile exe) or, for Flutter, native machine code per platform. For the web, dart compile js produces JavaScript and dart compile wasm targets WebAssembly. See What Is Dart? and Performance and Memory.

flowchart LR
    S["Dart source"] --> J["JIT in the Dart VM<br/>(development, hot reload)"]
    S --> A["AOT native code<br/>(release apps, servers)"]
    S --> W["JavaScript or WebAssembly<br/>(browsers)"]

One source, three common outputs.

30. What are the common Dart mistakes interviewers look for?

Overusing ! instead of handling null; forgetting await so a failure goes unnoticed (the unawaited_futures lint helps); mutating a final list and expecting immutability; overriding == without hashCode; leaving a StreamController unclosed; using dynamic where Object? would keep type checking; and doing heavy computation on the main isolate. See Common Dart Mistakes.

Try two of the ideas

TypeScript is not Dart, but a few of the ideas above have close equivalents. The first stand-in shows the null-aware operators of question 4. Strict mode forces you to handle undefined, similar to Dart's null safety:

TypeScript Null-aware operators (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The second stand-in compares final and const from question 2. readonly and Object.freeze play similar roles: the first stops reassignment, the second makes the object itself immutable:

TypeScript final versus const (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the result of final xs = [1, 2]; xs.add(3);?

    final only prevents assigning a new value to xs. The list object is mutable. Use const (or an unmodifiable list) for an immutable list.
  2. 2. Which statement about isolates is true?

    No shared memory means no data races. Messages are passed over ports, and Isolate.run wraps this in a Future-returning call.
  3. 3. What does late final x = compute(); do?

    A late variable with an initializer is lazily initialized, and a final one is assigned only once.
  4. 4. A class is declared sealed. What does that give you?

    All direct subtypes of a sealed class live in one library, so the compiler knows every case and can require them in a switch.

Summary

  • Know the vocabulary: sound null safety, final versus const, late, dynamic versus Object?, records and patterns.
  • For object-oriented questions, be ready to compare extends, implements and with, list the constructor kinds, and explain Dart 3 class modifiers.
  • For async, explain Futures, Streams, the microtask-then-event order and why isolates replace threads.
  • Mention gotchas (mutable final lists, timeouts that do not cancel, == without hashCode); they show real experience.
  • Practice by explaining each answer in your own words, not by memorizing sentences.

Finally, keep the syntax handy in the Dart Cheat Sheet.