Originally published at Shipped Code.
For Kotlin developers, Dart feels familiar within an hour: null safety, type inference, sealed classes, extension methods and named parameters all carry over. The trouble is the few differences that compile without a warning and still behave differently.
A Dart class has no data-class equality, so == compares identity until you override it or use a record. const builds one canonical compile-time object. Privacy is per library (usually one file) through a leading _, and there is no overloading. A started Future cannot be cancelled like a coroutine Job, because concurrency is one event loop per isolate.
TL;DR. Map your Kotlin habits with the table below. Then watch 2 things in Flutter code, state classes compared by identity (silent UI bugs) and a
Futurethat keeps running after the screen closes. Most other differences fail at compile time. The 2 that fail at runtime,addon aconstlist and reading alatefield too early, are in the gotchas list.
What you will learn:
- which Kotlin idioms map one to one and which only look the same
- the first compile and runtime errors you will meet
- what to do instead of cancelling a
Future
I write both Kotlin and Dart for client apps. The table and sections up to Async are the core, and the (Advanced) part can wait. Examples run on Dart 3.14.1, current stable as of writing (Flutter 3.50.1 ships Dart 3.14.0). For syntax from zero, see the language tour.
Kotlin to Dart mapping table
This is the Dart vs Kotlin cheat sheet I would have wanted on day 1. The right column is where the two only look the same.
| Kotlin | Dart | Watch out |
|---|---|---|
val x = 1 | final x = 1; | Same meaning: assigned once, object still mutable |
const val | const | Works on whole objects, not only primitives |
lateinit var | late | Also works on non-nullable int, bool; can be lazy |
data class | record, or class + ==/hashCode | No generated equals, copy or toString |
sealed class | sealed class | Same exhaustiveness; subclasses must be in the same library |
when | switch expression + patterns | Patterns can destructure objects, lists, maps |
fun String.x() | extension on String { ... } | Static dispatch, like Kotlin |
| default + named args | {required ...} named params | Named params must be declared in braces |
object | top-level variable or static | Top-level is the normal choice |
top-level private | _name | Private to the library (file), not the class; no internal equivalent |
| overloading | not supported | Use named or optional parameters |
suspend + coroutines | async + Future | No structured cancellation |
Flow | Stream | Single-subscription by default |
Equality on classes compares identity
A plain Dart class inherits == from Object, which checks identity. Two objects with the same fields are not equal.
class User { final String name; final int age; User(this.name, this.age); } void main() { final a = User('An', 30); final b = User('An', 30); print(a == b); final r1 = (name: 'An', age: 30); final r2 = (name: 'An', age: 30); print(r1 == r2); print(r1); } false true (age: 30, name: An) Records compare by value. The last line shows that toString lists named fields sorted by name, not in the order you wrote them. Do not parse it or rely on it in test snapshots.
For a real state class you write == and hashCode by hand, or generate them with freezed. Object.hash keeps the hand-written version short.
@override bool operator ==(Object other) => other is User && other.name == name && other.age == age; @override int get hashCode => Object.hash(name, age); With that override, a == User('An', 30) prints true and a Set of both holds 1 element. There is no generated copy either, so you add a copyWith method yourself.
Warning: state managers compare the old and new state to decide whether to rebuild. Bloc, for example, skips emitting a state that is
==to the current one. With identity equality, a "new" object with identical fields still triggers a rebuild, and mutating the old object in place and emitting it triggers none. Both bugs are silent.
final vs const
final is Kotlin's val. const goes further. The whole object is built at compile time, and every equal const expression gives back the same instance.
class Point { final int x, y; const Point(this.x, this.y); } void main() { print(identical(const Point(1, 2), const Point(1, 2))); print(identical(Point(1, 2), Point(1, 2))); final list = const [1, 2, 3]; list.add(4); } true false Unhandled exception: Unsupported operation: Cannot add to an unmodifiable list That last error came at runtime, not compile time. A const list has the static type List<int>, so add type-checks and only fails when it runs.
Canonical instances are why the Flutter lints ask for const widgets. A const Text('Hi') is created once, and Flutter can skip rebuilding a subtree whose widget is the identical instance it saw last frame.
Null safety: same idea, different tools
?., ?? and ! work as in Kotlin (?? is the Elvis operator). late is the closest thing to lateinit, and reading it too early throws.
class Session { late String token; } void main() { final s = Session(); print(s.token.length); } Unhandled exception: LateInitializationError: Field 'token' has not been initialized. The bigger habit to unlearn is smart casts on other objects' properties. Kotlin lets you check p.nickname != null on a val and use it afterwards. Dart refuses for public fields, even final ones, because a subclass could override the field with a getter that returns something else on the second read.
class Profile { final String? nickname; Profile(this.nickname); } void greet(Profile p) { if (p.nickname != null) { print(p.nickname.length); } } bin/promotion.dart:8:22: Error: Property 'length' cannot be accessed on 'String?' because it is potentially null. bin/promotion.dart:2:17: Context: 'nickname' refers to a public property so it couldn't be promoted. Copy the value into a local, or use a pattern that binds and checks in one step.
final nick = p.nickname; if (nick != null) print(nick.length); if (p case Profile(nickname: final n?)) print(n.toUpperCase()); Private final fields (_name) do get promoted since Dart 3.2, which is one more reason to keep state fields private.
No overloading, use named parameters
Two methods with the same name in one class do not compile.
bin/overload.dart:3:8: Error: 'log' is already declared in this scope. Dart solves the same problems with named parameters in braces, which can be required or have defaults, and positional optional parameters in square brackets.
void showToast(String message, {required Duration duration, bool top = false}) { print('$message for ${duration.inSeconds}s, top=$top'); } String initials(String first, [String? last]) => last == null ? first[0] : '${first[0]}${last[0]}'; void main() { showToast('Saved', duration: Duration(seconds: 2)); showToast('Offline', top: true, duration: Duration(seconds: 5)); print(initials('Duong', 'Vu')); print(initials('Vu')); } Saved for 2s, top=false Offline for 5s, top=true DV V Unlike Kotlin, a parameter is either positional or named by declaration, and the caller cannot switch. Also, functions do not need a class. Top-level functions and variables are normal Dart, so you rarely need an object or a companion.
Privacy is per library
A leading underscore makes a name private to its library, which is usually one file. Any code in that file can touch it, including code outside the class.
class Wallet { int _balance = 100; int get balance => _balance; } void cheat(Wallet w) => w._balance = 1000000; Calling cheat(w) from another file and printing w.balance gives 1000000. Reading w._balance from that other file fails.
bin/privacy.dart:7:11: Error: The getter '_balance' isn't defined for the type 'Wallet'. So _ works like Kotlin's private on a top-level declaration, visible to the whole file, and not like private inside a class. Dart has no internal. The convention is to put implementation files under a package's lib/src/ folder and not export them. part / part of splits one library across several files that share privacy, which is how code generators attach their output.
Sealed classes and patterns
Dart 3 sealed classes give you the same exhaustiveness check as Kotlin when, and patterns let one case destructure a field and match on its value.
sealed class Result<T> {} class Success<T> extends Result<T> { final T data; Success(this.data); } class Failure<T> extends Result<T> { final String message; final int? code; Failure(this.message, {this.code}); } class Loading<T> extends Result<T> {} String render(Result<List<String>> r) => switch (r) { Success(data: []) => 'Nothing yet', Success(:final data) => '${data.length} items', Failure(code: 401) => 'Please log in again', Failure(:final message) => 'Error: $message', }; I left out Loading on purpose, and the compiler names the missing case.
Error: The type 'Result<List<String>>' is not exhaustively matched by the switch cases since it doesn't match 'Loading<List<String>>()'. After adding Loading() => 'Loading...', render(Success(['a', 'b'])) returns 2 items and render(Failure('timeout', code: 401)) returns Please log in again. Records destructure the same way, so a function can return (int, String) and the caller writes final (id, name) = parse(line);. The details are in the patterns guide.
Async: a Future is not a Job
async/await reads like a suspend function, but the model underneath is different. Each isolate runs one event loop, and an await just schedules the rest of the function for later. There is no CoroutineScope, so nothing cancels child work when its parent goes away. If you are coming from Kotlin coroutines on Android, this is the part to slow down for.
This snippet gives up on a slow load after 400 ms, the way a screen might when the user leaves.
import 'dart:async'; Future<String> loadProfile() async { for (var i = 1; i <= 3; i++) { await Future.delayed(Duration(milliseconds: 300)); print(' loadProfile step $i'); } return 'profile'; } Future<void> main() async { try { await loadProfile().timeout(Duration(milliseconds: 400)); } on TimeoutException { print('timed out, screen closed'); } await Future.delayed(Duration(seconds: 1)); print('main done'); } loadProfile step 1 timed out, screen closed loadProfile step 2 loadProfile step 3 main done timeout only stops waiting. The work runs to the end, and in a real app that means network calls finishing and setState landing on a widget that is gone.
Warning: closing a screen does not stop its
Futures. Before touching state after anawait, checkmountedin aState(orcontext.mounted), or drop the result.
You have 3 practical options. Ignore the result when it is cheap. Check a flag between steps. Or wrap the work in CancelableOperation from package:async. CancelableOperation does less than its name suggests. cancel() makes op.value never complete, and it calls your onCancel, but the underlying work only stops if it checks op.isCanceled itself. In my test, a loop that checked the flag stopped at step 2, and the then callback on op.value never ran.
For streams, a Dart StreamController gives a single-subscription stream by default. A second listen throws Bad state: Stream has already been listened to. right away. Use StreamController.broadcast() when several listeners need the same events, roughly the role SharedFlow plays in Kotlin.
(Advanced) Isolates, class modifiers and reified generics
You can skip this part on day one.
Isolates instead of threads. Isolates do not share memory, so there are no locks and no dispatchers. For CPU-heavy work, Isolate.run runs a function on a new isolate and returns its result as a Future.
final result = await Isolate.run(() => fib(35)); The function and the values it captures are copied to the other isolate, so keep the closure small. On the web, Isolate.run is not available. The concurrency page has the full rules.
Class modifiers. Dart 3 added final, base, interface and mixin on classes. A Kotlin class is final by default. A Dart class is open by default, and a final class or interface class from another library cannot be extended.
Error: The class 'ApiClient' can't be extended outside of its library because it's a final class. Error: The class 'Cache' can't be extended outside of its library because it's an interface class. You can still implements Cache for a test fake. A final class blocks that too, which matters when you want to mock a package's client.
Reified generics. Dart keeps type arguments at runtime, so items is List<int> is true and items is List<String> is false for a <int>[1, 2, 3]. In Kotlin that check needs an inline function with reified.
Gotchas
- A state class without
==andhashCodecompares identity. Use a record, override both, or generate them. - A
constcollection compiles withaddand throws at runtime. -
latefields throwLateInitializationErroron early reads. Prefer a nullable field or a constructor parameter when the value may be missing. - No smart cast on public fields. Copy to a local or use a pattern.
-
_nameis visible to the whole file. -
Future.timeoutandCancelableOperation.canceldo not stop the work. Checkmountedafter everyawaitthat touches UI.
How these habits play out in a whole app decision is covered in Native or Flutter? How I choose for client apps. The series continues with Flutter widgets vs Jetpack Compose, which maps your Compose mental model to widgets, and later with Flutter state management compared and Networking with dio.

