Dart for Kotlin developers

Learn Dart 3 for Kotlin developers: null safety, async/await with Future and Stream, records, patterns and sealed classes mapped to Kotlin for Flutter. About 22 minutes.

Why it matters

  • Most Kotlin idioms have a Dart equivalent that looks similar but behaves differently: no suspend, no data class, no companion object, and generics that keep their type at runtime. Assuming a 1-to-1 mapping causes compile errors and subtle bugs in your first Flutter week.
  • Dart has no structured concurrency. A Future cannot be cancelled and is not tied to a scope, so work started from a Flutter screen keeps running after the user leaves. Kotlin developers used to viewModelScope cancelling everything are caught out by this.
  • Dart 3 sealed classes plus switch give you the same compile-time exhaustiveness as Kotlin when, but only with switch. An if-case chain is not checked, which is where missing branches slip through.
  • Flutter interviews ask "what replaces coroutines and Flow in Dart?" and "how does Dart null safety compare to Kotlin's?" to test whether you understand the model, not just the syntax.

The simple explanation

  • How is Dart different from Kotlin? Dart is a single-threaded, event-loop language per isolate. Async code uses Future and Stream with async/await, not coroutines.
  • Future<T> is like a Deferred<T> that has already started: you await it, but there is no launch, no scope and no cancellation.
  • Stream<T> is the closest thing to Flow<T>. Streams from an async* function start when someone listens, and pausing the subscription pauses the generator.
  • sealed class works like Kotlin's: subclasses must live in the same library, and a switch over the sealed type must handle every subclass.
  • Null safety is sound in both languages: String? means the same thing, ! in Dart is Kotlin's !!, and ?? is Kotlin's ?:.

Dart 3 code will look familiar to a Kotlin developer, but a few constructs do not map directly. The table maps the common ones.

KotlinDart 3Key difference
suspend funFuture<T> + async/awaitNo scope, no cancellation of a Future
Flow<T>Stream<T> + async*/yieldConsume with await for or listen; cancel the StreamSubscription
data classplain class, or a recordNo generated copyWith; classes compare by identity unless you override ==
sealed class + whensealed class + switchBoth exhaustive; Dart if-case is not
reified Tplain generic TNot needed: Dart generics keep their type at runtime
companion objectstatic membersNo companion object; top-level functions are common
lateinit var / by lazylate / late final x = ...Different exception on early read
val / varfinal / varconst is a separate compile-time constant

Three rules cover most of the confusion. First, no structured concurrency: a Future keeps running even if nobody awaits it, and a failure in one future passed to Future.wait does not stop the others. To stop work, cancel a StreamSubscription, use CancelableOperation from package:async, or use your HTTP client's own cancellation. Second, use switch for sealed types: a switch statement or expression on a sealed type is a compile error if a subclass is missing, while an if-case chain or a default branch silently skips that check. Third, one thread per isolate: async code still runs on the UI isolate; move CPU-heavy work to another isolate with Isolate.run.

Dart 3 records ((int, int) or ({int x, int y})) cover small one-off tuples where Kotlin would use Pair or a tiny data class. Records are immutable and compare by their fields, and they can be used anywhere a type can: fields, parameters, return values. For a real model class with copyWith, write it by hand or generate it with a package such as freezed.

const constructors create compile-time constants. Identical const expressions share one canonical instance, which Flutter uses to skip rebuilding unchanged widgets (covered in the widgets lesson).

Notes

  • Dart has no suspend keyword. An async function returns a Future<T>, and callers use await. There is no coroutineScope, launch or supervisorScope.
  • Stream<T> replaces Flow<T>. Produce one with async* and yield, consume it with await for or .listen(). Cancellation is manual via StreamSubscription.cancel(). Broadcast streams (many listeners) behave more like SharedFlow.
  • A Future cannot be cancelled. Future.wait reports an error, but the other futures still run to completion.
  • Dart 3 sealed class requires all direct subclasses in the same library. A switch statement or expression over it is checked for exhaustiveness; adding a subclass breaks the build until every switch handles it.
  • if-case (if (result case Ok(:final value))) is handy for one branch but is never exhaustive. Do not use an if-case chain where you want the compiler to catch a missing subclass.
  • Records: positional (int, String) fields are read with .$1, .$2; named ({int x, String y}) with .x, .y. Destructure with patterns: final (x, y) = point;.
  • late in Dart throws LateInitializationError on an early read; Kotlin lateinit var throws UninitializedPropertyAccessException. late final x = compute(); is lazy, like Kotlin by lazy.
  • Dart generics are reified: value is T and List<int> checks work at runtime in any generic function, so there is no need for Kotlin's inline + reified trick.
  • Named parameters are optional by default. A non-nullable named parameter with no default must be marked required, otherwise it does not compile.
  • Dart has no companion object, no object declarations and no by delegation. Every class also defines an implicit interface; Dart 3 adds class modifiers (interface, base, final, sealed) and mixin classes to control how a class can be extended or implemented.

Code example

A Dart 3 repository a Kotlin developer would write instead of suspend fun + Flow: a sealed class for results, Future/Stream for async, and a switch expression that the compiler checks for exhaustiveness.

// Dart 3: Future and Stream instead of suspend and Flow.
 
sealed class ApiResult<T> {
  const ApiResult();
}
 
final class Ok<T> extends ApiResult<T> {
  const Ok(this.value);
  final T value;
}
 
final class Err<T> extends ApiResult<T> {
  const Err(this.message);
  final String message;
}
 
class UserRepository {
  // Like a suspend fun: callers await it.
  Future<ApiResult<String>> fetchUser(int id) async {
    try {
      await Future<void>.delayed(const Duration(milliseconds: 300));
      return Ok('User $id');
    } catch (e) {
      return Err(e.toString());
    }
  }
 
  // Like a cold Flow: runs when someone listens.
  Stream<ApiResult<String>> watchUser(int id) async* {
    yield Ok('User $id connected');
  }
}
 
String describe(ApiResult<String> result) => switch (result) {
      // Exhaustive: adding a new subclass makes this a compile error.
      Ok(:final value) => 'Got: $value',
      Err(:final message) => 'Failed: $message',
    };
 
Future<void> main() async {
  final repo = UserRepository();
  print(describe(await repo.fetchUser(42)));
 
  await for (final update in repo.watchUser(42)) {
    print(describe(update));
  }
 
  // A record instead of a one-off data class.
  final (int, int) point = (10, 20);
  final (px, py) = point;
  print('Record: $px, $py');
}
  • sealed class ApiResult<T> with final class subclasses mirrors a Kotlin sealed class. The switch expression in describe is exhaustive, exactly like when used as an expression.
  • Ok(:final value) is an object pattern: it checks the type and binds the value field in one step, like is Ok -> result.value with a smart cast.
  • fetchUser returns Future<ApiResult<String>> and is called with await, like a suspend fun. Nothing cancels it if the caller goes away.
  • watchUser is an async* generator. await for consumes it like collect; breaking out of the loop cancels the subscription.

Run the idea in plain Kotlin

// Kotlin side of the mapping: sealed + when (Dart: sealed + switch),
// data class vs plain class equality (Dart: record vs plain class).

sealed interface ApiResult
data class Ok(val value: String) : ApiResult
data class Err(val message: String) : ApiResult

fun describe(result: ApiResult): String = when (result) {
  is Ok -> "Got: " + result.value
  is Err -> "Failed: " + result.message
}

class PlainPoint(val x: Int, val y: Int)
data class DataPoint(val x: Int, val y: Int)

// Models Dart Future.wait: every task runs to the end,
// then the first error is reported. Nothing is cancelled.
fun dartStyleWait(tasks: List<Pair<String, Boolean>>): List<String> {
  val log = mutableListOf<String>()
  var firstError: String? = null
  for ((name, ok) in tasks) {
      if (ok) log.add(name + " finished") else {
          log.add(name + " failed")
          if (firstError == null) firstError = name
      }
  }
  log.add("Future.wait error: " + firstError)
  return log
}

fun main() {
  println(describe(Ok("User 42")))
  println(describe(Err("timeout")))

  println("plain class equal: " + (PlainPoint(1, 2) == PlainPoint(1, 2)))
  println("data class equal: " + (DataPoint(1, 2) == DataPoint(1, 2)))

  dartStyleWait(listOf("A" to true, "B" to false, "C" to true)).forEach { println(it) }
}

Expected output:

Got: User 42
Failed: timeout
plain class equal: false
data class equal: true
A finished
B failed
C finished
Future.wait error: B
  • The when expression is the Kotlin twin of the Dart switch expression above: both fail to compile if a sealed subtype is missing.
  • PlainPoint behaves like a plain Dart class (identity equality); DataPoint behaves like a Dart record (field equality).
  • dartStyleWait models the Dart rule that a failed future does not stop its siblings. In Kotlin coroutineScope, task B's failure would cancel A and C.

In production

setState() called after dispose() on a profile screen
  • Error logs showed setState() called after dispose() from a profile screen, plus profile requests that kept completing after users had navigated away.
  • The screen started fetchUser() in initState and called setState when the Future completed. If the user left first, the State was already disposed.
  • The team had assumed, as with viewModelScope, that leaving the screen would cancel the request. A Dart Future has no owner and is never cancelled.
The fix
  • Checked if (!mounted) return; after every await before touching setState or context.
  • Wrapped the request in CancelableOperation from package:async and cancelled it in dispose, so the result is ignored once the screen is gone.
  • Moved loading into a state holder (Riverpod, Bloc or a ChangeNotifier) whose lifetime is managed outside the widget, covered in the state management lesson.
Missing branch after adding a sealed subclass
  • A Timeout subclass was added to the ApiResult sealed hierarchy. On slow networks users saw a blank screen, with no error logged.
  • The UI used an if-case chain that handled Ok and Err. if-case is never checked for exhaustiveness, so Timeout fell through and nothing was shown.
  • Tests only covered Ok and Err, so nothing failed in CI.
The fix
  • Replaced the if-case chain with a switch expression over ApiResult with no default branch.
  • The build then failed at every switch that did not handle Timeout, and each one was fixed.
  • Added a team rule: branch on sealed types with switch, never if-case chains or default, so new subclasses are caught at compile time.

Common mistakes

  • Expecting a Future to be cancelled with the screen. A Future is not tied to any scope. Check mounted after each await, cancel StreamSubscriptions in dispose, and use CancelableOperation or your HTTP client's cancellation for long requests.
  • Branching on a sealed type with if-case. Only switch is checked for exhaustiveness. A default or _ case also turns the check off. Use a switch without a catch-all when you want new subclasses to break the build.
  • Writing Kotlin-style generic workarounds. Dart generics are reified, so value is T just works. Passing a Type token or a factory to get around erasure is unnecessary in Dart.
  • Expecting == to compare fields. A plain Dart class uses identity equality, unlike a Kotlin data class. Override == and hashCode, use a record, or generate them with freezed.
  • Leaving out required on a named parameter. Named parameters are optional by default. A non-nullable one without a default does not compile; marking it nullable to make the error go away just moves the problem to runtime. Use required.
  • Doing heavy work in an async function and expecting it off the UI thread. async does not mean background. Parsing a large JSON file in an async function still blocks the UI isolate. Use Isolate.run (or Flutter's compute) for CPU-heavy work.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does Dart null safety compare to Kotlin null safety?”

“What replaces Kotlin coroutines and Flow in Dart?”

“What are Dart 3 sealed classes and how do they compare with Kotlin's?”

“How do you model a Kotlin data class in Dart?”

Quiz

You pass three Futures to Future.wait and one of them fails. What happens to the other two?

What is the closest Dart 3 replacement for a Kotlin data class?

A new subclass is added to a Dart 3 sealed class. Which code fails to compile until it handles the new subclass?

What does Dart throw when you read a late variable before it is assigned?

0 of 4 answered

Mini task

15-minute exercise: Rewrite a Kotlin repository in Dart 3

Goal: Take a small Kotlin suspend/Flow repository and rewrite it in Dart 3 with Future/Stream, a sealed class and a switch expression.

  1. Write the Kotlin version (3 min). A UserRepository with suspend fun fetchUser(id: Int): ApiResult and fun watchUser(id: Int): Flow<ApiResult>, where ApiResult is a sealed class with Ok and Err.

  2. Translate to Dart 3 (5 min). Replace suspend fun with Future<ApiResult<String>> + async/await, and Flow with Stream<ApiResult<String>> + async*/yield. Replace when with a switch expression that has no default branch.

  3. Add a record (2 min). Replace a one-off data class Point(val x: Int, val y: Int) with a record (int, int) and destructure it with final (x, y) = point;.

  4. Check exhaustiveness (2 min). Add a third subclass Timeout. Run dart analyze and confirm the switch expression is now an error. Write the same logic as an if-case chain and confirm it compiles without complaint. Then handle Timeout in the switch.

  5. Check async behaviour (3 min). In main, call Future.wait on two Future.delayed calls where one throws after 100 ms and the other prints a message after 500 ms. Catch the error and confirm the second message still prints.

Done condition: dart analyze reports no issues, the switch handles all three subclasses, and you saw the second future finish even though the first one failed.

Next: Widgets and the widget tree