Dart for Kotlin developers
Why it matters
- Most Kotlin idioms have a Dart equivalent that looks similar but behaves differently: no
suspend, nodata class, nocompanion 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
Futurecannot 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 toviewModelScopecancelling everything are caught out by this. - Dart 3
sealedclasses plusswitchgive you the same compile-time exhaustiveness as Kotlinwhen, but only withswitch. Anif-casechain is not checked, which is where missing branches slip through. - Flutter interviews ask "what replaces coroutines and
Flowin 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
FutureandStreamwithasync/await, not coroutines. Future<T>is like aDeferred<T>that has already started: youawaitit, but there is nolaunch, no scope and no cancellation.Stream<T>is the closest thing toFlow<T>. Streams from anasync*function start when someone listens, and pausing the subscription pauses the generator.sealed classworks like Kotlin's: subclasses must live in the same library, and aswitchover 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.
| Kotlin | Dart 3 | Key difference |
|---|---|---|
suspend fun | Future<T> + async/await | No scope, no cancellation of a Future |
Flow<T> | Stream<T> + async*/yield | Consume with await for or listen; cancel the StreamSubscription |
data class | plain class, or a record | No generated copyWith; classes compare by identity unless you override == |
sealed class + when | sealed class + switch | Both exhaustive; Dart if-case is not |
reified T | plain generic T | Not needed: Dart generics keep their type at runtime |
companion object | static members | No companion object; top-level functions are common |
lateinit var / by lazy | late / late final x = ... | Different exception on early read |
val / var | final / var | const 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
suspendkeyword. Anasyncfunction returns aFuture<T>, and callers useawait. There is nocoroutineScope,launchorsupervisorScope. Stream<T>replacesFlow<T>. Produce one withasync*andyield, consume it withawait foror.listen(). Cancellation is manual viaStreamSubscription.cancel(). Broadcast streams (many listeners) behave more likeSharedFlow.- A
Futurecannot be cancelled.Future.waitreports an error, but the other futures still run to completion. - Dart 3
sealed classrequires all direct subclasses in the same library. Aswitchstatement or expression over it is checked for exhaustiveness; adding a subclass breaks the build until everyswitchhandles it. if-case(if (result case Ok(:final value))) is handy for one branch but is never exhaustive. Do not use anif-casechain 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;. latein Dart throwsLateInitializationErroron an early read; Kotlinlateinit varthrowsUninitializedPropertyAccessException.late final x = compute();is lazy, like Kotlinby lazy.- Dart generics are reified:
value is TandList<int>checks work at runtime in any generic function, so there is no need for Kotlin'sinline+reifiedtrick. - 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, noobjectdeclarations and nobydelegation. Every class also defines an implicit interface; Dart 3 adds class modifiers (interface,base,final,sealed) andmixinclasses 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>withfinal classsubclasses mirrors a Kotlinsealed class. Theswitchexpression indescribeis exhaustive, exactly likewhenused as an expression.Ok(:final value)is an object pattern: it checks the type and binds thevaluefield in one step, likeis Ok -> result.valuewith a smart cast.fetchUserreturnsFuture<ApiResult<String>>and is called withawait, like asuspend fun. Nothing cancels it if the caller goes away.watchUseris anasync*generator.await forconsumes it likecollect; 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
whenexpression is the Kotlin twin of the Dartswitchexpression above: both fail to compile if a sealed subtype is missing. PlainPointbehaves like a plain Dart class (identity equality);DataPointbehaves like a Dart record (field equality).dartStyleWaitmodels the Dart rule that a failed future does not stop its siblings. In KotlincoroutineScope, task B's failure would cancel A and C.
In production
- 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()ininitStateand calledsetStatewhen theFuturecompleted. If the user left first, theStatewas already disposed. - The team had assumed, as with
viewModelScope, that leaving the screen would cancel the request. A DartFuturehas no owner and is never cancelled.
- Checked
if (!mounted) return;after everyawaitbefore touchingsetStateorcontext. - Wrapped the request in
CancelableOperationfrompackage:asyncand cancelled it indispose, 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.
- A
Timeoutsubclass was added to theApiResultsealed hierarchy. On slow networks users saw a blank screen, with no error logged. - The UI used an
if-casechain that handledOkandErr.if-caseis never checked for exhaustiveness, soTimeoutfell through and nothing was shown. - Tests only covered
OkandErr, so nothing failed in CI.
- Replaced the
if-casechain with aswitchexpression overApiResultwith nodefaultbranch. - The build then failed at every
switchthat did not handleTimeout, and each one was fixed. - Added a team rule: branch on sealed types with
switch, neverif-casechains ordefault, so new subclasses are caught at compile time.
Common mistakes
- Expecting a Future to be cancelled with the screen. A
Futureis not tied to any scope. Checkmountedafter eachawait, cancelStreamSubscriptions indispose, and useCancelableOperationor your HTTP client's cancellation for long requests. - Branching on a sealed type with if-case. Only
switchis checked for exhaustiveness. Adefaultor_case also turns the check off. Use aswitchwithout a catch-all when you want new subclasses to break the build. - Writing Kotlin-style generic workarounds. Dart generics are reified, so
value is Tjust works. Passing aTypetoken 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==andhashCode, use a record, or generate them withfreezed. - 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.
asyncdoes not mean background. Parsing a large JSON file in anasyncfunction still blocks the UI isolate. UseIsolate.run(or Flutter'scompute) 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.
-
Write the Kotlin version (3 min). A
UserRepositorywithsuspend fun fetchUser(id: Int): ApiResultandfun watchUser(id: Int): Flow<ApiResult>, whereApiResultis a sealed class withOkandErr. -
Translate to Dart 3 (5 min). Replace
suspend funwithFuture<ApiResult<String>>+async/await, andFlowwithStream<ApiResult<String>>+async*/yield. Replacewhenwith aswitchexpression that has nodefaultbranch. -
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 withfinal (x, y) = point;. -
Check exhaustiveness (2 min). Add a third subclass
Timeout. Rundart analyzeand confirm theswitchexpression is now an error. Write the same logic as anif-casechain and confirm it compiles without complaint. Then handleTimeoutin theswitch. -
Check async behaviour (3 min). In
main, callFuture.waiton twoFuture.delayedcalls 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.