Skip to the content.

Flutter Cheat Sheet: Dart, Widgets, Layout, State Management, Navigation and Networking

A practical Flutter and Dart cheat sheet with copy-ready snippets for the things you look up every day: Dart syntax (null safety, records, patterns, dot shorthands), core widgets, layout, theming, forms, state management (setState, ValueNotifier, Provider, Riverpod, Bloc), navigation with go_router, HTTP networking and JSON, local storage, animations, testing, CLI commands and fixes for the most common errors. It is for developers building iOS, Android, web and desktop apps with Flutter, from first app to production.

Last reviewed: December 2026 (Flutter 3.50, Dart 3.14). Flutter 3.50 deprecates the Material and Cupertino libraries bundled in the SDK in favor of the material_ui and cupertino_ui packages; see Imports in Flutter 3.50+. Snippets were reviewed against the official docs but not compiled in CI; please report anything that no longer builds.

Table of Contents


CLI commands

Task Command
Check your setup flutter doctor -v
New app flutter create my_app (--org com.example sets the bundle id prefix)
New package / plugin flutter create --template=package my_pkg / --template=plugin
List devices flutter devices
Run (debug, hot reload) flutter run (press r hot reload, R hot restart, q quit)
Run on a device flutter run -d chrome / -d macos / -d <device-id>
Add a dependency flutter pub add http (dev: flutter pub add --dev mocktail)
Update dependencies flutter pub upgrade (--major-versions to bump constraints)
See outdated packages flutter pub outdated
Analyze flutter analyze
Apply automated fixes dart fix --apply
Format dart format .
Run tests flutter test (--coverage for lcov)
Code generation dart run build_runner build --delete-conflicting-outputs
Android release flutter build appbundle (Play Store) / flutter build apk --split-per-abi
iOS release flutter build ipa
Web release flutter build web (--wasm to compile to WebAssembly)
Desktop release flutter build macos / windows / linux
Clean build files flutter clean
Upgrade Flutter flutter upgrade
Open DevTools Printed by flutter run, or dart devtools

Build modes: debug (hot reload, assertions, slow), profile (--profile, for performance measurement on a real device) and release (--release, optimized, no debugging).

Imports in Flutter 3.50+

Flutter 3.50 formally deprecates the in-SDK Material and Cupertino libraries. New code should use the standalone packages:

flutter pub add material_ui
flutter pub add cupertino_ui
// New (Flutter 3.50+)
import 'package:material_ui/material_ui.dart';
import 'package:cupertino_ui/cupertino_ui.dart';

// Older code (still works in 3.50, with deprecation warnings)
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

Migrate an existing app with dart fix --apply --code=migrate_design_widgets, then run flutter pub add for the packages if the fix did not add them. The official migration guide also describes a temporary MaterialUiCompatibilityBridge for apps whose dependencies have not migrated yet.

The snippets below use material_ui; if you are on Flutter 3.47 or earlier, replace the import with package:flutter/material.dart. Widget names and APIs are the same.


Dart essentials

// Variables
var name = 'Ada';            // type inferred (String), can be reassigned
final city = 'London';       // set once at runtime
const pi = 3.14159;          // compile-time constant
late final String token;     // initialized later, before first use
int count = 0;
double ratio = 0.5;
bool done = false;
dynamic anything = 1;        // opt out of static checks (avoid)

// Null safety
String? nickname;            // may be null
final len = nickname?.length ?? 0;   // null-aware access + default
nickname ??= 'Anon';                 // assign if null
final forced = nickname!;            // assert non-null (throws if null)

// Strings
final greeting = 'Hello, $name! You have ${count + 1} messages.';
final multi = '''
Line one
Line two''';
final raw = r'C:\path\no\escapes';

// Collections
final list = <int>[1, 2, 3];
final set = {'a', 'b'};
final map = {'id': 1, 'name': 'Ada'};
final doubled = list.map((n) => n * 2).toList();
final evens = list.where((n) => n.isEven).toList();
final total = list.fold(0, (sum, n) => sum + n);
final combined = [...list, 4, if (done) 5, for (final n in list) n * 10];

// Functions
int add(int a, int b) => a + b;
void greet(String name, {String greeting = 'Hi', required bool loud}) {}
void log(String msg, [String level = 'info']) {}   // optional positional
greet('Ada', loud: true);

// Classes
class User {
  final String id;
  final String name;
  const User({required this.id, required this.name});

  User copyWith({String? name}) => User(id: id, name: name ?? this.name);

  @override
  String toString() => 'User($id, $name)';
}

// Inheritance, interfaces, mixins
abstract class Shape { double get area; }
class Square extends Shape {
  final double side;
  Square(this.side);
  @override
  double get area => side * side;
}
mixin Loggable { void log(String m) => print('[${runtimeType}] $m'); }
class Service with Loggable {}

// Async
Future<String> fetchName() async {
  await Future.delayed(const Duration(seconds: 1));
  return 'Ada';
}

Stream<int> ticker() async* {
  for (var i = 0; i < 3; i++) {
    await Future.delayed(const Duration(seconds: 1));
    yield i;
  }
}

// Errors
try {
  final value = int.parse('abc');
} on FormatException catch (e) {
  print('Bad number: ${e.message}');
} catch (e, stack) {
  print('Unexpected: $e');
} finally {
  print('done');
}

Modern Dart features

Feature Since Dart Example
Records 3.0 (String, int) pair = ('Ada', 36); and named ({int x, int y}) p = (x: 1, y: 2);
Patterns and destructuring 3.0 final (name, age) = pair;
Switch expressions 3.0 final label = switch (code) { 200 => 'OK', 404 => 'Not found', _ => 'Error' };
Sealed classes (exhaustive switch) 3.0 sealed class Result {}
Class modifiers 3.0 final class, interface class, base class
Extension types 3.3 extension type UserId(String value) {} (zero-cost wrapper)
Digit separators 3.6 const million = 1_000_000;
Wildcard variables 3.7 list.forEach((_) => count++); with multiple _ parameters allowed
Null-aware elements 3.8 [?maybeNull, 'always'] adds the first only if non-null
Dot shorthands 3.10 mainAxisAlignment: .center instead of MainAxisAlignment.center
Primary constructors 3.13 class Point(final int x, final int y);

Sealed classes + switch for app states

sealed class LoadState<T> {}
class Loading<T> extends LoadState<T> {}
class Loaded<T> extends LoadState<T> {
  final T data;
  Loaded(this.data);
}
class Failed<T> extends LoadState<T> {
  final Object error;
  Failed(this.error);
}

Widget build(LoadState<List<String>> state) => switch (state) {
  Loading() => const CircularProgressIndicator(),
  Loaded(:final data) => Text('${data.length} items'),
  Failed(:final error) => Text('Error: $error'),
};  // the compiler checks every case is handled

Dot shorthands in widget code (Dart 3.10+)

Container(
  alignment: .center,                  // Alignment.center
  padding: const .all(16),             // EdgeInsets.all(16)
  child: Column(
    mainAxisAlignment: .center,        // MainAxisAlignment.center
    crossAxisAlignment: .start,        // CrossAxisAlignment.start
    children: [Text('Hi', style: TextStyle(fontWeight: .bold))],
  ),
);

Shorthands only work where the expected type is known (a typed parameter). Your package’s SDK constraint must allow the language version that introduced the feature (environment: sdk: ^3.10.0 for dot shorthands, ^3.13.0 for primary constructors).

Primary constructors (Dart 3.13+)

class Point(final int x, final int y);                 // fields + constructor in one line
class const Size(final double width, final double height);  // const primary constructor

final p = Point(1, 2);
print(p.x); // 1

Widgets 101

import 'package:material_ui/material_ui.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo)),
      home: const CounterPage(),
    );
  }
}

class CounterPage extends StatefulWidget {
  const CounterPage({super.key});

  @override
  State<CounterPage> createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter')),
      body: Center(child: Text('$_count', style: Theme.of(context).textTheme.displayMedium)),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() => _count++),
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

StatelessWidget vs StatefulWidget

  StatelessWidget StatefulWidget
Holds mutable state No Yes, in its State object
Rebuilds when Parent rebuilds or an inherited dependency changes Also when you call setState
Use for Pure UI from inputs Controllers, animations, local UI state

State lifecycle

Method When Typical use
initState() Once, when inserted Create controllers, start listening (no context-dependent inherited lookups yet)
didChangeDependencies() After initState and when an inherited widget changes Read Theme.of, MediaQuery and similar
build() Every rebuild Return widgets; keep it fast and side-effect free
didUpdateWidget(old) Parent rebuilt with new config React to changed constructor arguments
dispose() Removed permanently Dispose controllers, cancel subscriptions and timers
class _SearchState extends State<Search> {
  final _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose(); // always dispose controllers you create
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => TextField(controller: _controller);
}

Keys

const everywhere you can

const widgets are created once and skipped during rebuilds. Enable the prefer_const_constructors lint (included in flutter_lints) and let dart fix add them.


Layout cheat sheet

Need Widget
Horizontal / vertical line of children Row / Column
Fill remaining space Expanded(child: ...) (flex: 2 for proportions)
Take space only if needed Flexible(child: ...)
Fixed gap SizedBox(width: 8) / SizedBox(height: 8), or spacing: on Row/Column
Padding Padding(padding: EdgeInsets.all(16), child: ...)
Center Center or Align(alignment: Alignment.topRight)
Overlap Stack + Positioned
Wrap to next line Wrap(spacing: 8, runSpacing: 8, children: ...)
Scroll one child SingleChildScrollView
Long or infinite lists ListView.builder / ListView.separated
Grids GridView.builder with SliverGridDelegateWithMaxCrossAxisExtent
Collapsing headers and mixed scrolling CustomScrollView + SliverAppBar, SliverList, SliverGrid
Size constraints ConstrainedBox, SizedBox, AspectRatio, FractionallySizedBox
React to available space LayoutBuilder
Screen size MediaQuery.sizeOf(context)
Safe from notches SafeArea
Column(
  crossAxisAlignment: CrossAxisAlignment.stretch,
  spacing: 12, // gap between children
  children: [
    const Text('Title'),
    Row(
      children: [
        const Icon(Icons.person),
        const SizedBox(width: 8),
        Expanded(child: Text(longName, overflow: TextOverflow.ellipsis)),
        IconButton(icon: const Icon(Icons.more_vert), onPressed: () {}),
      ],
    ),
    Expanded(
      child: ListView.separated(
        itemCount: items.length,
        separatorBuilder: (_, _) => const Divider(height: 1),
        itemBuilder: (context, i) => ListTile(
          key: ValueKey(items[i].id),
          title: Text(items[i].title),
          subtitle: Text(items[i].subtitle),
          trailing: const Icon(Icons.chevron_right),
          onTap: () {},
        ),
      ),
    ),
  ],
)

The layout rule to remember: constraints go down, sizes go up, parent sets position. A widget can only be as big as its parent allows, which explains most overflow and “unbounded height” errors (see Common errors).


Common widgets by task

Task Widgets
Page structure Scaffold, AppBar, Drawer, NavigationBar (bottom), NavigationRail (side), BottomAppBar
Text Text, RichText / Text.rich, SelectableText
Buttons FilledButton, ElevatedButton, OutlinedButton, TextButton, IconButton, FloatingActionButton, SegmentedButton
Images Image.asset, Image.network, CircleAvatar, Icon
Inputs TextField, TextFormField, Checkbox, Switch, Radio + RadioGroup, Slider, DropdownMenu, DatePickerDialog via showDatePicker
Containers Container, Card, DecoratedBox, ClipRRect, Material
Lists ListTile, ExpansionTile, Dismissible, ReorderableListView
Feedback SnackBar, AlertDialog, showModalBottomSheet, Tooltip, CircularProgressIndicator, LinearProgressIndicator
Gestures InkWell (with ripple), GestureDetector (raw)
// SnackBar
ScaffoldMessenger.of(context).showSnackBar(
  SnackBar(content: const Text('Saved'), action: SnackBarAction(label: 'Undo', onPressed: undo)),
);

// Confirm dialog that returns a value
final ok = await showDialog<bool>(
  context: context,
  builder: (context) => AlertDialog(
    title: const Text('Delete item?'),
    content: const Text('This cannot be undone.'),
    actions: [
      TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
      FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('Delete')),
    ],
  ),
);
if (ok == true && context.mounted) { /* delete */ }

// Bottom sheet
showModalBottomSheet(
  context: context,
  showDragHandle: true,
  builder: (context) => const Padding(padding: EdgeInsets.all(24), child: Text('Options')),
);

// Radio buttons (RadioGroup owns the selected value; per-Radio groupValue is deprecated)
RadioGroup<String>(
  groupValue: _size,
  onChanged: (value) => setState(() => _size = value!),
  child: Column(children: [
    RadioListTile(value: 'S', title: const Text('Small')),
    RadioListTile(value: 'L', title: const Text('Large')),
  ]),
)

Theming and dark mode

MaterialApp(
  theme: ThemeData(
    colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF3F51B5)),
    textTheme: const TextTheme(bodyMedium: TextStyle(fontSize: 15)),
  ),
  darkTheme: ThemeData(
    colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF3F51B5), brightness: Brightness.dark),
  ),
  themeMode: ThemeMode.system, // or .light / .dark from user settings
)

// Read theme values
final colors = Theme.of(context).colorScheme;
final text = Theme.of(context).textTheme;
Container(color: colors.primaryContainer, child: Text('Hi', style: text.titleLarge?.copyWith(color: colors.onPrimaryContainer)));

// Transparency (withOpacity is deprecated)
final faded = colors.primary.withValues(alpha: 0.5);

// State-dependent button styles
FilledButton(
  style: ButtonStyle(
    backgroundColor: WidgetStateProperty.resolveWith(
      (states) => states.contains(WidgetState.disabled) ? Colors.grey : colors.primary,
    ),
  ),
  onPressed: null,
  child: const Text('Disabled'),
)

Material 3 is the default design system. Prefer colorScheme roles (primary, onPrimary, surface, surfaceContainer, error…) over hard-coded colors so dark mode and dynamic color work automatically.


Forms and input

class SignUpForm extends StatefulWidget {
  const SignUpForm({super.key});
  @override
  State<SignUpForm> createState() => _SignUpFormState();
}

class _SignUpFormState extends State<SignUpForm> {
  final _formKey = GlobalKey<FormState>();
  final _email = TextEditingController();
  final _password = TextEditingController();
  bool _obscure = true;

  @override
  void dispose() {
    _email.dispose();
    _password.dispose();
    super.dispose();
  }

  void _submit() {
    if (!_formKey.currentState!.validate()) return;
    // send _email.text and _password.text
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        spacing: 16,
        children: [
          TextFormField(
            controller: _email,
            decoration: const InputDecoration(labelText: 'Email', border: OutlineInputBorder()),
            keyboardType: TextInputType.emailAddress,
            autofillHints: const [AutofillHints.email],
            textInputAction: TextInputAction.next,
            validator: (v) => (v == null || !v.contains('@')) ? 'Enter a valid email' : null,
          ),
          TextFormField(
            controller: _password,
            obscureText: _obscure,
            decoration: InputDecoration(
              labelText: 'Password',
              border: const OutlineInputBorder(),
              suffixIcon: IconButton(
                icon: Icon(_obscure ? Icons.visibility : Icons.visibility_off),
                onPressed: () => setState(() => _obscure = !_obscure),
              ),
            ),
            autofillHints: const [AutofillHints.newPassword],
            validator: (v) => (v == null || v.length < 8) ? 'At least 8 characters' : null,
            onFieldSubmitted: (_) => _submit(),
          ),
          FilledButton(onPressed: _submit, child: const Text('Create account')),
        ],
      ),
    );
  }
}

Tips: wrap long forms in SingleChildScrollView so the keyboard does not cause overflow; dismiss the keyboard with FocusScope.of(context).unfocus(); group fields in AutofillGroup for password managers.


State management

Approach Best for Ceremony Package
setState State used by one widget None Built in
ValueNotifier + ValueListenableBuilder One value shared by a few widgets Low Built in
ChangeNotifier + ListenableBuilder A small model object Low Built in
InheritedWidget Passing data down the tree Medium Built in
Provider Dependency injection + ChangeNotifier models; the classic recommendation in the docs Low provider
Riverpod Compile-safe providers, async state, testing, no BuildContext needed to read state Medium flutter_riverpod
Bloc / Cubit Event-driven, strict separation, large teams Higher flutter_bloc

Best picks: start with setState and ValueNotifier. When state is shared across screens, use Provider (simplest) or Riverpod (stronger guarantees, great for async data). Choose Bloc when your team wants explicit events and states for every change.

ValueNotifier (built in)

final counter = ValueNotifier<int>(0);

ValueListenableBuilder<int>(
  valueListenable: counter,
  builder: (context, value, _) => Text('$value'),
);

counter.value++; // rebuilds only the builder above

ChangeNotifier + Provider

class Cart extends ChangeNotifier {
  final _items = <String>[];
  List<String> get items => List.unmodifiable(_items);
  void add(String item) {
    _items.add(item);
    notifyListeners();
  }
}

// Above the widgets that need it:
ChangeNotifierProvider(create: (_) => Cart(), child: const MyApp());

// Read and rebuild on change:
final count = context.watch<Cart>().items.length;
// Call methods without rebuilding:
context.read<Cart>().add('Book');
// Rebuild only when a derived value changes:
final hasItems = context.select<Cart, bool>((c) => c.items.isNotEmpty);

Riverpod

final todosProvider = FutureProvider<List<Todo>>((ref) async {
  return ref.watch(apiProvider).fetchTodos();
});

void main() => runApp(const ProviderScope(child: MyApp()));

class TodoList extends ConsumerWidget {
  const TodoList({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final todos = ref.watch(todosProvider);
    return todos.when(
      data: (items) => ListView(children: [for (final t in items) ListTile(title: Text(t.title))]),
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (e, _) => Center(child: Text('Error: $e')),
    );
  }
}

Cubit (flutter_bloc)

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);
  void increment() => emit(state + 1);
}

BlocProvider(create: (_) => CounterCubit(), child: const CounterView());

BlocBuilder<CounterCubit, int>(builder: (context, count) => Text('$count'));
context.read<CounterCubit>().increment();

Check each package’s documentation for its current major version API; Riverpod and Bloc both evolve and their docs show the recommended style.


// Push a page
Navigator.push(context, MaterialPageRoute(builder: (_) => DetailPage(id: item.id)));

// Push and wait for a result
final picked = await Navigator.push<String>(context, MaterialPageRoute(builder: (_) => const PickerPage()));
if (!context.mounted) return; // the widget may be gone after an await

// Return a result
Navigator.pop(context, 'blue');

// Replace / clear history (e.g. after login)
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => const HomePage()));
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => const HomePage()), (route) => false);
final router = GoRouter(
  initialLocation: '/',
  redirect: (context, state) {
    final loggedIn = auth.isLoggedIn;
    final goingToLogin = state.matchedLocation == '/login';
    if (!loggedIn && !goingToLogin) return '/login';
    if (loggedIn && goingToLogin) return '/';
    return null; // no redirect
  },
  routes: [
    GoRoute(path: '/', builder: (context, state) => const HomePage()),
    GoRoute(path: '/login', builder: (context, state) => const LoginPage()),
    GoRoute(
      path: '/items/:id',
      builder: (context, state) => ItemPage(id: state.pathParameters['id']!),
    ),
  ],
);

MaterialApp.router(routerConfig: router);

// Navigate
context.go('/items/42');     // replace the current location (like a URL change)
context.push('/items/42');   // push on top (back button returns)
context.pop();

Use StatefulShellRoute in go_router for bottom navigation bars that keep each tab’s history.

Intercept the back button

PopScope(
  canPop: !hasUnsavedChanges,
  onPopInvokedWithResult: (didPop, result) async {
    if (didPop) return;
    final leave = await confirmDiscard(context);
    if (leave && context.mounted) Navigator.pop(context);
  },
  child: const EditorPage(),
)

(WillPopScope was replaced by PopScope for Android predictive back support.)


Networking and JSON

flutter pub add http
import 'dart:convert';
import 'package:http/http.dart' as http;

class Todo {
  final int id;
  final String title;
  final bool completed;
  const Todo({required this.id, required this.title, required this.completed});

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
        id: json['id'] as int,
        title: json['title'] as String,
        completed: json['completed'] as bool? ?? false,
      );

  Map<String, dynamic> toJson() => {'id': id, 'title': title, 'completed': completed};
}

class ApiClient {
  ApiClient({http.Client? client, this.baseUrl = 'https://api.example.com'}) : _client = client ?? http.Client();
  final http.Client _client;
  final String baseUrl;

  Future<List<Todo>> fetchTodos() async {
    final res = await _client
        .get(Uri.parse('$baseUrl/todos'), headers: {'Accept': 'application/json'})
        .timeout(const Duration(seconds: 10));
    if (res.statusCode != 200) {
      throw HttpException('GET /todos failed: ${res.statusCode}');
    }
    final list = jsonDecode(res.body) as List<dynamic>;
    return list.map((e) => Todo.fromJson(e as Map<String, dynamic>)).toList();
  }

  Future<Todo> createTodo(String title) async {
    final res = await _client.post(
      Uri.parse('$baseUrl/todos'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'title': title}),
    );
    if (res.statusCode != 201) throw HttpException('POST /todos failed: ${res.statusCode}');
    return Todo.fromJson(jsonDecode(res.body) as Map<String, dynamic>);
  }
}

class HttpException implements Exception {
  HttpException(this.message);
  final String message;
  @override
  String toString() => message;
}

Async UI: FutureBuilder and StreamBuilder

class TodoScreen extends StatefulWidget {
  const TodoScreen({super.key, required this.api});
  final ApiClient api;
  @override
  State<TodoScreen> createState() => _TodoScreenState();
}

class _TodoScreenState extends State<TodoScreen> {
  late Future<List<Todo>> _future;

  @override
  void initState() {
    super.initState();
    _future = widget.api.fetchTodos(); // create the Future once, NOT inside build()
  }

  Future<void> _refresh() async {
    setState(() => _future = widget.api.fetchTodos());
    await _future;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Todo>>(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasError) {
          return Center(child: Text('Something went wrong: ${snapshot.error}'));
        }
        final todos = snapshot.data!;
        return RefreshIndicator(
          onRefresh: _refresh,
          child: ListView.builder(
            itemCount: todos.length,
            itemBuilder: (_, i) => CheckboxListTile(value: todos[i].completed, onChanged: null, title: Text(todos[i].title)),
          ),
        );
      },
    );
  }
}
StreamBuilder<int>(
  stream: ticker(),
  builder: (context, snapshot) => Text(snapshot.hasData ? 'Tick ${snapshot.data}' : 'Waiting...'),
)

Creating the Future inside build() re-runs the request on every rebuild, the most common FutureBuilder bug.


Local storage

Need Package Notes
Small key-value settings shared_preferences Not for secrets or large data
Secrets (tokens) flutter_secure_storage Keychain / Keystore backed
Relational data sqflite or drift Drift adds type-safe queries, migrations and streams
Files path_provider + dart:io App documents and cache directories
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('onboarded', true);
final onboarded = prefs.getBool('onboarded') ?? false;

Animations

Type Widgets Use for
Implicit (automatic) AnimatedContainer, AnimatedOpacity, AnimatedAlign, AnimatedSwitcher, TweenAnimationBuilder Animate when a value changes; no controller
Explicit AnimationController + Tween + AnimatedBuilder / FadeTransition Looping, sequenced or gesture-driven animation
Shared element Hero Image flying between screens
Physics SpringSimulation, DraggableScrollableSheet Natural motion
// Implicit: change the values, Flutter animates
AnimatedContainer(
  duration: const Duration(milliseconds: 300),
  curve: Curves.easeOut,
  width: expanded ? 240 : 120,
  height: 48,
  decoration: BoxDecoration(
    color: expanded ? Colors.indigo : Colors.grey,
    borderRadius: BorderRadius.circular(expanded ? 24 : 8),
  ),
)

// Switch between widgets with a fade
AnimatedSwitcher(duration: const Duration(milliseconds: 200), child: Text('$count', key: ValueKey(count)))

// Explicit: a pulsing icon
class Pulse extends StatefulWidget {
  const Pulse({super.key});
  @override
  State<Pulse> createState() => _PulseState();
}

class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
  late final _controller = AnimationController(vsync: this, duration: const Duration(seconds: 1))..repeat(reverse: true);

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => ScaleTransition(
        scale: Tween(begin: 0.9, end: 1.1).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut)),
        child: const Icon(Icons.favorite, color: Colors.red, size: 48),
      );
}

Responsive and adaptive layouts

LayoutBuilder(
  builder: (context, constraints) {
    if (constraints.maxWidth >= 840) return const TwoPaneLayout();   // large screens
    if (constraints.maxWidth >= 600) return const RailLayout();      // medium
    return const BottomNavLayout();                                  // compact
  },
)
Window width Material 3 size class Navigation pattern
< 600 dp Compact NavigationBar at the bottom
600 to 839 dp Medium NavigationRail
840 dp and up Expanded NavigationRail or a permanent NavigationDrawer, two panes

Prefer MediaQuery.sizeOf(context) over MediaQuery.of(context).size: it rebuilds only when the size changes. Use LayoutBuilder when a widget should adapt to its own available space rather than the whole screen. Check Theme.of(context).platform or defaultTargetPlatform for platform-specific behavior, and test with large text scaling (accessibility settings).


Testing

// test/counter_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/main.dart';

void main() {
  testWidgets('increments the counter', (tester) async {
    await tester.pumpWidget(const MyApp());

    expect(find.text('0'), findsOneWidget);
    await tester.tap(find.byTooltip('Increment'));
    await tester.pump(); // rebuild after the tap

    expect(find.text('1'), findsOneWidget);
  });
}
Test type Package Runs Use for
Unit test / flutter_test Dart VM, fast Models, parsing, business logic
Widget flutter_test Headless, fast One screen or component
Integration integration_test Real device or emulator Full flows, performance
Golden flutter_test (matchesGoldenFile) Headless Visual regressions

Useful finders and actions: find.byType(ListTile), find.byKey(const Key('save')), find.textContaining('Error'), tester.enterText(finder, 'hello'), tester.drag(finder, const Offset(0, -300)), tester.pumpAndSettle() (wait for animations). Mock HTTP by injecting MockClient from package:http/testing.dart into your API class.


Performance tips

Tip Why
Use const constructors Skips rebuilding unchanged subtrees
Use ListView.builder for long lists Builds only visible items
Split big build methods into small widgets Smaller rebuild scope (better than helper methods returning widgets)
Watch only what you need (context.select, ValueListenableBuilder) Fewer rebuilds
Avoid Opacity and ClipPath in animations Expensive offscreen passes; use FadeTransition or AnimatedOpacity
Size images (cacheWidth, cacheHeight) Decoding huge images wastes memory
Move heavy work to isolates (Isolate.run, compute) Keeps 60/120 fps
Profile in --profile mode on a real device Debug mode is not representative
Use the DevTools Performance and Widget Rebuild views Find jank and needless rebuilds

Common errors and fixes

Error Cause Fix
A RenderFlex overflowed by N pixels Children wider/taller than the Row/Column Wrap with Expanded/Flexible, use TextOverflow.ellipsis, or make it scrollable
Vertical viewport was given unbounded height ListView inside a Column Wrap the list in Expanded, or give it a fixed height
setState() called after dispose() Async work finished after the widget was removed Check if (!mounted) return; before setState
Don't use 'BuildContext's across async gaps (lint) Using context after await Check context.mounted first
No MaterialLocalizations found / No Directionality widget found Widget used outside MaterialApp Wrap in MaterialApp (or Directionality in tests)
Null check operator used on a null value ! on something null Handle the null case, or initialize earlier
ProviderNotFoundException Reading a provider above where it is provided Move the provider higher, or use the right BuildContext
Incorrect use of ParentDataWidget Expanded not directly inside a Flex (Row/Column) Make it a direct child of the Row/Column
Looking up a deactivated widget's ancestor is unsafe Using a stale context (e.g. after pop) Capture what you need before navigating
Keyboard covers the text field Scaffold cannot scroll Use a scrollable body; keep resizeToAvoidBottomInset: true
CERTIFICATE_VERIFY_FAILED Bad TLS chain on the server or emulator clock Fix the server certificate; never disable verification in production
Network works in debug, fails in release on Android Missing INTERNET permission in main/AndroidManifest.xml Add the permission

Packages worth knowing

All on pub.dev, the official package repository. Check scores, maintenance and platform support before adding a dependency.

Package Purpose
go_router Declarative routing, deep links, web URLs
provider / flutter_riverpod / flutter_bloc State management
http / dio Networking
json_serializable / freezed JSON and immutable models via code generation
shared_preferences / flutter_secure_storage Key-value and secure storage
drift / sqflite SQLite databases
cached_network_image Image caching
url_launcher Open links, email, phone
intl Dates, numbers, translations
flutter_lints Recommended lint rules
mocktail Mocks for tests without code generation

FAQ

Is Flutter good for production apps? Yes. Flutter targets iOS, Android, web, Windows, macOS and Linux from one codebase and is used in many production apps. Evaluate platform-specific needs (native SDKs, app size, web SEO) for your case.

Which state management should I learn first? setState and ValueNotifier, then Provider or Riverpod. Learn Bloc if your team or job uses it. The concepts (lifting state up, immutable state, rebuilding only what changed) transfer between them.

Do I need to migrate to material_ui now? In Flutter 3.50 the bundled libraries are deprecated but still work. Migrate when convenient using dart fix --apply --code=migrate_design_widgets; new projects should start with the packages.

Hot reload vs hot restart? Hot reload (r) injects code changes and keeps state. Hot restart (R) restarts the app and resets state; needed after changing main(), global initializers or initState logic.

How do I reduce app size? Build an app bundle (flutter build appbundle) so the store delivers only the needed native code, use --split-debug-info with --obfuscate, compress images and remove unused packages and assets. Measure with flutter build apk --analyze-size --target-platform android-arm64.

Flutter or React Native? Both build cross-platform apps. Flutter renders its own widgets for pixel-consistent UI and uses Dart; React Native uses platform views and JavaScript/TypeScript with React. Teams usually choose by existing language skills and UI requirements.

How do I call native code? Platform channels or the Pigeon code generator for typed messages; FFI (ffigen) for C libraries; jnigen for Java/Kotlin APIs. The docs have a native interop section covering these options.

Why does my web build look blurry or load slowly? Try the WebAssembly build (flutter build web --wasm) on supported browsers, serve with compression and correct caching headers, and keep the initial route light.


Where to go next

  1. Follow the official Flutter docs learning pathway, and the codelabs for guided projects.
  2. Learn the language properly with the Dart language tour.
  3. Read understanding constraints to master layout.
  4. Study the official app architecture guide before your app grows.
  5. Browse the widget catalog and the Flutter API reference.
  6. Keep up with what’s new in the docs and the breaking changes list when you upgrade.
  7. Profile your app with Flutter DevTools.

Contributing

PRs are welcome. Keep entries accurate: test snippets with the current stable Flutter (flutter create a scratch app and paste them in), note the minimum Flutter or Dart version for new features, and link to the official docs or pub.dev for packages.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.