Flutter cheat sheet

Revise Flutter: Future/Stream async, widget tree with const and setState, Riverpod/Bloc state, go_router, MethodChannel, and rendering performance.

Key ideas

  1. Widgets are immutable: never call a setter; return a new widget from build(), just like Compose, unlike Android View.
  2. Future<T> cannot be cancelled; check mounted after every await and cancel StreamSubscription in dispose().
  3. Dart 3 sealed class + switch gives compile-time exhaustiveness; if-case does not, so a missing subclass goes unnoticed.
  4. const on a widget canonicalises it so the framework skips the subtree on rebuild; const on TextStyle or EdgeInsets only avoids an allocation.
  5. context.watch<T>() subscribes the widget; context.read<T>() does not. In Riverpod, use ref.watch in build and ref.read in callbacks.
  6. Navigator.of(context) returns the nearest navigator; pass rootNavigator: true for full-screen dialogs and root-level routes.
  7. MethodChannel handlers run on the main thread; move slow work to a coroutine with Dispatchers.IO or a background TaskQueue.
  8. ListView.builder is lazy (like RecyclerView); ListView(children: [...]) builds every child up front.
  9. Dart generics are reified: value is T works at runtime in any generic function, so the Kotlin inline + reified trick is unnecessary.
  10. setState runs 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 termUse it for
Future<T> / awaitAsync replacement for Kotlin suspend; callers await, no coroutineScope or launch.
Stream<T> / async* / yieldReplacement for Flow<T>; consume with await for or .listen(), cancel via StreamSubscription.cancel().
sealed class + switchExhaustive type checking; adding a subclass breaks the build until every switch handles it.
setStateRun 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.readRiverpod: 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.replaceDeclarative 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 / receiveBroadcastStreamNative-to-Dart stream; cancel the StreamSubscription in dispose() to trigger onCancel.
ListView.builderLazy list (like RecyclerView); builds only visible items plus a small cache extent (250 logical pixels by default).
Isolate.run / computeOffload 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 time

Riverpod 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 switch over if-case for sealed types so the compiler catches a missing subclass.
  • Never call invokeMethod from build(); fetch once in initState or a state holder and render the result.
  • Prefer ListView.builder over ListView(children: [...]) for any list longer than a handful of items.
  • Never create a ChangeNotifier or Bloc inside build(); create it in a provider's create callback so it survives rebuilds.
  • Prefer ref.watch in build and ref.read in event handlers; ref.read inside build does not subscribe.
  • Never use GlobalKey for ordinary list items; use ValueKey(id) or ObjectKey(item) for stable identity.

Gotchas

  • Calling setState after an await without a mounted check. The State may have been disposed while the Future was pending, causing a runtime error. Fix: add if (!mounted) return; after every await and cancel subscriptions in dispose().
  • Branching on a sealed type with if-case instead of switch. if-case is never exhaustive, so a new subclass compiles silently and the branch is missed. Fix: use a switch without a default or _ 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: true or navigate through go_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] or copyWith.
  • Forgetting to cancel an EventChannel StreamSubscription in dispose(). onCancel never 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() in dispose().
  • Using WillPopScope in new code. It is deprecated and cannot support Android's predictive back gesture. Fix: use PopScope with canPop and onPopInvokedWithResult, and opt in with android: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.

Go deeper