Flutter cheat sheet
Key ideas
- Widgets are immutable: never call a setter; return a new widget from
build(), just like Compose, unlike AndroidView. Future<T>cannot be cancelled; checkmountedafter everyawaitand cancelStreamSubscriptionindispose().- Dart 3
sealed class+switchgives compile-time exhaustiveness;if-casedoes not, so a missing subclass goes unnoticed. conston a widget canonicalises it so the framework skips the subtree on rebuild;constonTextStyleorEdgeInsetsonly avoids an allocation.context.watch<T>()subscribes the widget;context.read<T>()does not. In Riverpod, useref.watchinbuildandref.readin callbacks.Navigator.of(context)returns the nearest navigator; passrootNavigator: truefor full-screen dialogs and root-level routes.MethodChannelhandlers run on the main thread; move slow work to a coroutine withDispatchers.IOor a backgroundTaskQueue.ListView.builderis lazy (likeRecyclerView);ListView(children: [...])builds every child up front.- Dart generics are reified:
value is Tworks at runtime in any generic function, so the Kotlininline+reifiedtrick is unnecessary. setStateruns its callback synchronously and marks the element dirty; the rebuild happens on the next frame, so several calls in one frame produce one rebuild.
APIs at a glance
| API or term | Use it for |
|---|---|
Future<T> / await | Async replacement for Kotlin suspend; callers await, no coroutineScope or launch. |
Stream<T> / async* / yield | Replacement for Flow<T>; consume with await for or .listen(), cancel via StreamSubscription.cancel(). |
sealed class + switch | Exhaustive type checking; adding a subclass breaks the build until every switch handles it. |
setState | Run a state change and mark the State dirty; the rebuild runs on the next frame. |
context.watch<T>() / context.read<T>() | watch subscribes the widget to a Provider; read is a one-time lookup without subscription. |
ref.watch / ref.read | Riverpod: watch in build for reactive data, read in event handlers like onPressed. |
Navigator.of(context, rootNavigator: true) | Get the root navigator instead of the nearest one; needed for full-screen dialogs. |
go_router / context.go / context.push / context.replace | Declarative routing; go replaces the stack, push adds to it, replace swaps the top page. |
MethodChannel / invokeMethod<T> | One-shot request-reply to native; returns Future<T?>, handle null and PlatformException. |
EventChannel / receiveBroadcastStream | Native-to-Dart stream; cancel the StreamSubscription in dispose() to trigger onCancel. |
ListView.builder | Lazy list (like RecyclerView); builds only visible items plus a small cache extent (250 logical pixels by default). |
Isolate.run / compute | Offload CPU-heavy work (large JSON parse, image processing) off the main isolate. |
Snippets
Sealed class with exhaustive switch
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;
}
String describe(ApiResult<String> result) => switch (result) {
Ok(:final value) => 'Loaded $value',
Err(:final message) => 'Failed: $message',
}; // adding a third subclass breaks this switch at compile timeRiverpod AsyncNotifier with mounted guard
class UserRepository {
Future<String> fetchName() async => 'Ada';
}
final userRepositoryProvider = Provider((ref) => UserRepository());
final userProvider = AsyncNotifierProvider<UserNotifier, String>(UserNotifier.new);
class UserNotifier extends AsyncNotifier<String> {
@override
Future<String> build() => ref.watch(userRepositoryProvider).fetchName();
Future<void> refresh() async {
state = const AsyncLoading();
final result = await AsyncValue.guard(
() => ref.read(userRepositoryProvider).fetchName(),
);
if (!ref.mounted) return;
state = result;
}
}go_router with auth redirect
final isLoggedIn = ValueNotifier<bool>(false);
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) => const Scaffold(body: Text('Login'));
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) => const Scaffold(body: Text('Home'));
}
final router = GoRouter(
initialLocation: '/',
refreshListenable: isLoggedIn,
redirect: (context, state) {
if (!isLoggedIn.value && state.matchedLocation != '/login') {
return '/login';
}
return null;
},
routes: [
GoRoute(path: '/login', builder: (_, __) => const LoginScreen()),
GoRoute(path: '/', builder: (_, __) => const HomeScreen()),
],
);MethodChannel wrapper with error handling
class NativeBridge {
static const _method = MethodChannel('com.example/native_bridge');
Future<String> getDeviceId() async {
try {
final id = await _method.invokeMethod<String>('getDeviceId');
return id ?? 'unknown';
} on PlatformException catch (e) {
throw Exception('Native call failed (${e.code}): ${e.message}');
}
}
}Rules of thumb
- Prefer
switchoverif-casefor sealed types so the compiler catches a missing subclass. - Never call
invokeMethodfrombuild(); fetch once ininitStateor a state holder and render the result. - Prefer
ListView.builderoverListView(children: [...])for any list longer than a handful of items. - Never create a
ChangeNotifierorBlocinsidebuild(); create it in a provider'screatecallback so it survives rebuilds. - Prefer
ref.watchinbuildandref.readin event handlers;ref.readinsidebuilddoes not subscribe. - Never use
GlobalKeyfor ordinary list items; useValueKey(id)orObjectKey(item)for stable identity.
Gotchas
- Calling setState after an await without a mounted check. The
Statemay have been disposed while theFuturewas pending, causing a runtime error. Fix: addif (!mounted) return;after everyawaitand cancel subscriptions indispose(). - Branching on a sealed type with if-case instead of switch.
if-caseis never exhaustive, so a new subclass compiles silently and the branch is missed. Fix: use aswitchwithout adefaultor_catch-all. - Calling Navigator.of(context) from inside a nested Navigator. It returns the nearest navigator, so the route is pushed onto the inner stack instead of the root. Fix: pass
rootNavigator: trueor navigate throughgo_router. - Mutating a list in place and emitting the same instance in Riverpod or Bloc. Both compare states with
==, and an object is always equal to itself, so no rebuild happens. Fix: emit a new immutable object with[...state, item]orcopyWith. - Forgetting to cancel an EventChannel StreamSubscription in dispose().
onCancelnever fires on the native side, so sensors and listeners stay registered, draining battery and sending events to a gone screen. Fix: store the subscription and call.cancel()indispose(). - Using WillPopScope in new code. It is deprecated and cannot support Android's predictive back gesture. Fix: use
PopScopewithcanPopandonPopInvokedWithResult, and opt in withandroid:enableOnBackInvokedCallback="true"in the manifest.
Quick interview answers
How does Dart async differ from Kotlin coroutines?
Dart has no suspend keyword; an async function returns a Future<T> and callers use await. There is no coroutineScope, launch, or supervisorScope, and a Future cannot be cancelled, so you must guard with mounted checks and cancel StreamSubscriptions manually.
Why are Flutter widgets immutable, and how does that compare to Android Views?
Widgets are immutable value objects; you never call a setter, you return a new widget from build(). This is the opposite of the Android View model where you call setText() on the same object, and is close to how Jetpack Compose works.
What is the difference between context.watch and context.read in Provider, and the Riverpod equivalents?
context.watch<T>() subscribes the calling widget so it rebuilds when the provider changes, while context.read<T>() is a one-time lookup without subscription. In Riverpod the rule is the same: use ref.watch inside build for reactive data and ref.read inside event handlers like onPressed.
How does go_router handle authentication redirects, and why is refreshListenable important?
A top-level redirect callback runs on every navigation, including deep-link arrivals, and can return a location string to redirect or null to continue. Without refreshListenable wired to your auth notifier, logging in or out does not move the user until the next navigation, so a logged-out user can stay on a protected screen.
When should you use Isolate.run or compute in Flutter?
Use them for CPU-heavy work such as parsing a large JSON file or processing images, because async does not move work off the UI isolate. Running that work on the main isolate blocks build and layout, dropping frames, so offload it with Isolate.run or Flutter's compute.
What is the correct way to handle a MethodChannel call on the Android side?
Register the handler in FlutterActivity.configureFlutterEngine via binaryMessenger, and remember that handlers run on the main thread, so move slow work to a coroutine with Dispatchers.IO or a background TaskQueue. Every call must receive exactly one reply (success, error, or notImplemented); a missing reply leaves the Dart Future waiting forever, and a second reply throws.