Skip to content
Software Atlas

Flutter

Dart for JavaScript developers, widgets, constraints-based layout, state, navigation, loading and sending data, shared state, a complete small app, testing and shipping. Every snippet compiled and tested against Flutter 3.47.

⏱ ~150 min read, in passes23 sections14 interactive widgets + quizDart · Flutter 3.47
Sections are tagged by level:FoundationsPractitionerStaff-level
Foundations§01

The 30-second version

You know JavaScript and React. You want an app on both iPhone and Android, and someone said "use Flutter". This page takes you from zero to building real screens, in the order you need things, and every code sample on it was compiled and tested against Flutter 3.47.

In one sentenceFlutter is a toolkit for building apps from one Dart codebase. It does not ask the phone to draw buttons and lists. It gets a blank canvas from the operating system and paints every pixel itself.

The other two ways to build an app make the difference clear. Switch between them:

Who draws the button?
Three ways to build the same screen. Follow the layers from your code down to the glass.
Your code
Dart and widgets: one codebase
Flutter framework (Dart)
works out every size and position, and what to paint
Flutter engine (C++)
turns the paint commands into pixels
A blank canvas from the OS
the OS's toolkit is not asked to draw anything
GPU → screen
you write thisships inside your apppart of the phone's operating system
What a “button” is here: Pixels painted by Flutter. FilledButton is ordinary Dart code in the framework; it looks the same on every phone because the OS never draws it.

In Flutter everything on screen is a widget: a small Dart object that describes a piece of UI. If you know React, a widget plays the role of both the component and the element it returns. You will build screens by putting widgets inside widgets.

What you get, and what you give up

You getYou give up
One codebase for Android and iOS (and web, Windows, macOS, Linux)The engine ships inside your app, so even a tiny app is several megabytes bigger than a native one
Pixel-identical UI on every device and OS versionYour widgets are not the platform's native controls. A new look in the next iOS release does not appear in your app by itself
Hot reload: save a file, see the change in under a second, keep the app's stateA new language. Dart is easy to pick up from JavaScript (§03 and §04), but your npm packages don't come along
Full control of every pixel, and smooth animation by defaultPlatform features (camera, payments, Bluetooth) go through a plugin or a bit of Kotlin/Swift (§19)

How to read this page

It is long, because it is meant to be the one page you need. You do not have to read it in one go, and you should not read all of it before you build something.

1

First pass: enough to build an app

§02 setup. §03 and §04 Dart. §06 widgets, §07 layout, §08 state. §10 context, up to its "stop here" box. §11 lists, §12 input, §13 navigation, §14 loading and sending data. §15 up to and including provider. Then §17, which assembles all of it into one small app.
2

Second pass: when you hit the problem

§05 (Dart you meet in other people's code). §09 the three trees and the end of §10, when state behaves strangely. The rest of §15 when you choose a state package. §16 testing, once your first app runs; the test at the end of §17 waits for it.
3

Before you ship

§18 keeping it fast. §19 phone features, building and the stores. §21 pitfalls is worth skimming early: you will recognise the errors when they come. §22 quiz, §23 cheat sheet.

Every second-pass section or part starts with a box that says so, and tells you what, if anything, you need from it right now.

Foundations§02

Setup and your first run

In one sentenceFour commands get you a running app: flutter doctor, flutter create, cd, flutter run. After that you mostly press r.

Install, then ask the doctor

Install the Flutter SDK by following the guide for your operating system at docs.flutter.dev (the tool prints that address itself). The SDK contains everything Dart: the language, the flutter command and the framework source. It does not contain the tools that build the Android and iOS shells around your app:

  • Android: install Android Studio. It brings the Android SDK and an emulator, a phone that runs in a window on your computer. Works on Windows, macOS and Linux.
  • iOS: you need a Mac with Xcode, which includes Apple's version of an emulator, called a simulator. An iOS app cannot be built on Windows or Linux; on those systems flutter build does not even list the iOS commands.

Then run flutter doctor. It checks each tool and tells you what is missing. This is the real output on a fresh Linux machine with only the SDK installed:

flutter doctor on Flutter 3.47.9, nothing else installed yet (shortened)
[✓] Flutter (Channel stable, 3.47.9, on Ubuntu 24.04.5 LTS 6.18.44-fc-v378, locale en_US)
[✗] Android toolchain - develop for Android devices
    ✗ Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
[✓] Chrome - develop for the web
[✗] Linux toolchain - develop for Linux desktop
[✓] Connected device (2 available)
[✓] Network resources

! Doctor found issues in 2 categories.

Fix the lines for the platforms you care about and ignore the rest. You don't need a green tick everywhere.

Create a project

flutter create my_app     # prints "Wrote 131 files." and "All done!"
cd my_app

Here is what those files are. You will spend almost all your time in the first three.

PathWhat it is
lib/main.dartYour app. All your Dart code goes in lib/.
pubspec.yamlThe project file: app name, version, packages, bundled images and fonts. Flutter's package.json. (pubspec.yaml)
test/widget_test.dartOne example test (§16).
analysis_options.yamlWhich lint rules the Linter applies. It turns on the recommended set from the flutter_lints package.
android/, ios/A small native app for each platform that hosts Flutter (the embedder). You open these rarely: for permissions, app icons, signing.
web/, windows/, macos/, linux/The same idea for the other platforms. Delete the folders you don't target, or pass --platforms=android,ios to flutter create.
pubspec.lockThe exact package versions that were resolved, like package-lock.json. (Lockfile) Commit it.

Run it

Run the generated app before you change anything. Start an emulator or simulator, or connect a phone by cable (on Android you first switch on "USB debugging" in the phone's developer settings). Then:

flutter devices    # lists what Flutter can run on
flutter run        # builds, installs and starts the app on the device it found

The first build is slow, because the native shell around your app has to be compiled. When it finishes you see a counter app, and the terminal stays attached to it and shows a short list of keys. These are the ones you'll use:

KeyWhat the tool calls itWhat it does
rHot reloadLoad your changed code into the running app. State is kept.
RHot restartStart your Dart code again from main(). State is lost.
qQuitStop the app on the device.
dDetachStop flutter run but leave the app running.

Editors with the Flutter extension (VS Code, Android Studio) hot reload every time you save, so in practice you rarely press r yourself.

What you are running

This is the generated lib/main.dart, with its long explanatory comments removed. It is the counter: a button that adds one to a number.

lib/main.dart from flutter create (comments removed)
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(colorScheme: .fromSeed(seedColor: Colors.deepPurple)),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: .center,
          children: [
            const Text('You have pushed the button this many times:'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

Don't try to understand every line yet. Sections 03 to 10 cover all of it. For now, notice three things:

  1. main() is where the program starts, and runApp(…) hands Flutter the first widget.
  2. Everything is a class with a build method that returns more widgets, nested like JSX: Scaffold(appBar: …, body: Center(child: Column(children: […]))).
  3. setState wraps the line that changes _counter. That call is what makes the number on screen update (§08).

Hot reload, hot restart, full restart

Hot reload is the feature that makes Flutter pleasant to work in. It is close to hot module replacement on the web, with one important difference in what survives. Step through a real run. The code panel uses Dart you have not learned yet (it is taught in §03 to §08); for now follow the three panels on the right and the text under them.

Hot reload and hot restart, step by step
A real run of this program on Flutter 3.47: what each key keeps and what it throws away.
Code
1final String greeting = 'final v1'; // a global: set once, on first use
2const String label = 'const v1'; // a compile-time constant
3
4void main() {
5 runApp(const App());
6}
7
8class App extends StatefulWidget {
9 const App({super.key});
10
11 @override
12 State<App> createState() => _AppState();
13}
14
15class _AppState extends State<App> {
16 int _count = 0; // state: lives in memory while the app runs
17 late final Timer _timer;
18
19 @override
20 void initState() {
21 super.initState();
22 _timer = Timer.periodic(const Duration(seconds: 1), (_) {
23 setState(() => _count++);
24 });
25 }
26
27 @override
28 void dispose() {
29 _timer.cancel();
30 super.dispose();
31 }
32
33 @override
34 Widget build(BuildContext context) {
35 return Text(
36 'build v1 · count $_count · $greeting · $label',
37 textDirection: TextDirection.ltr,
38 );
39 }
40}
On the screen
nothing yet
In the app's memory
nothing yet
What ran
main()
You type flutter run. In debug mode your Dart code runs in the Dart VM, a program that can compile code while it runs. It starts at main(), which hands the first widget to Flutter.
1 / 8
New codeKeeps app stateRuns main() and initState() againTypical time
Hot reload (r)✓✓✗well under a second
Hot restart (R)✓✗✓under a second for a small app, a few seconds for a big one
Full restart (stop, then flutter run)✓, plus native code✗✓from several seconds to minutes

initState() is the method where a widget sets itself up; you will meet it in §08.

Why hot reload works in debug and not in release

flutter run builds in debug mode. Your Dart code then runs in the Dart VM, which compiles code while the app is running (JIT). A program that can compile code at run time can also accept new code at run time. That is all hot reload needs.

A release build is compiled completely to machine code before it ships (AOT). It starts faster and runs faster, but there is no compiler inside it any more, so nothing can be reloaded. Debug mode also runs thousands of extra checks called assertions, which is why a debug build feels slower than the real app will.

Build modeCommandFor
Debugflutter runDevelopment: hot reload, assertions, debugger. Slow.
Profileflutter run --profileMeasuring performance on a real phone (§18).
Releaseflutter run --release, flutter build …What users get (§19).

Then: switch to the material_ui package

Your app runs. Before you write your own code, make one change to the project. It needs some explaining, because Flutter is in the middle of a move.

The first line of lib/main.dart imports Flutter's Material widgets: MaterialApp, Scaffold, buttons, app bars. For years they were part of the SDK, in the library package:flutter/material.dart. They now also exist as an ordinary package called material_ui, which can be updated without waiting for a Flutter release. This is the situation in Flutter 3.47.9:

  • The old library is not deprecated. flutter create writes it, the analyzer has no complaint about it, and most tutorials and answers you will find use it.
  • The move has been announced in the SDK. It ships an automatic fix named "Migrate from flutter/material.dart to material_ui/material_ui.dart". No date for removing the old library is given.
  • Popular packages have already moved. go_router switched in version 18.0.0 and flutter_riverpod in 3.5.0; both now build their screens with material_ui. Not every package has moved yet.
  • The two libraries contain classes with the same names that are different classes. MaterialApp from one is not MaterialApp from the other, and the same goes for Theme, Scaffold and the rest.

That last point is what forces a choice. Nothing fails to compile if you stay on the old library, but two things silently go wrong as soon as you add a package that has moved. Both were measured in this page's test project:

  • go_router 18 no longer sees a Material app. It looks for material_ui's MaterialApp, does not find one, and falls back to plain pages: screens are swapped with an instant cut instead of the platform's slide animation, and its built-in error screen is the unstyled one.
  • Your theme stops at the border. A colour scheme you set with the old ThemeData is invisible to any widget that asks material_ui for the theme. Such a widget gets the default purple.

So use one library in the whole app. This page uses material_ui, because §13 and §15 use go_router 18 and flutter_riverpod 3.5. The Dart SDK does the switch for you:

flutter pub add material_ui
dart fix --apply --code=migrate_design_widgets

The first command adds the package to pubspec.yaml and downloads it (pub is Dart's package manager, the npm of Dart). Its output ends with Changed 4 dependencies!. The second rewrites the import in every file and reports:

lib/main.dart
  migrate_design_widgets - 1 fix

test/widget_test.dart
  migrate_design_widgets - 1 fix

2 fixes made in 2 files.

Check that it worked: search the project for flutter/material.dart. There must be no hits. lib/main.dart now starts with import 'package:material_ui/material_ui.dart';, pubspec.yaml contains the lines below, and flutter run shows the same counter as before.

pubspec.yaml (part)
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  material_ui: ^1.11.0

^1.11.0 means "version 1.11.0 or any newer 1.x".

Foundations§03

Dart for JavaScript developers, part 1: values and functions

In one sentenceDart reads like JavaScript with types. The big difference is when mistakes are caught: a wrong type or a forgotten null stops the build, before the app ever runs.

The rest of this page is written in Dart, so this section and the next teach the parts of it you need. Everything is shown as "the JavaScript you know, then the Dart". If you have used TypeScript, most of this will feel familiar.

The first differences

JavaScriptDart
Runs from the top of the fileStarts at a function called main()
Semicolons are optionalSemicolons are required
console.log(x)print(x); in a Flutter app, debugPrint('…')
let / constvar / final, plus a stronger const
One number typeint and double
`Hi ${name}` (backticks only)'Hi $name' or 'Hi ${user.name}' in ordinary quotes
===== (there is no ===)
null and undefinedonly null
function add(a, b) { … }int add(int a, int b) { … }
PromiseFuture (§04)
import { x } from "./file.js"import 'file.dart'; (§04)

A first program

hello.dart
void main() {
  final language = 'Dart';
  debugPrint('Hello from $language'); // Flutter's console.log
}

Variables: var, final, const

var name = 'Ada'; // type inferred as String; can be reassigned
final startedAt = DateTime.now(); // set once, value worked out at run time
const maxItems = 20; // set once, value fixed when the code is compiled

int count = 0; // you can also write the type yourself
double price = 9.5;
bool isOpen = true;
String title = 'Inbox';

Dart has static types: every variable has one type for its whole life. You rarely have to write it, because of type inference: var name = 'Ada' makes name a String exactly as if you had written String name = 'Ada'. Assign a number to it later and the build fails with:

A value of type 'int' can't be assigned to a variable of type 'String'.

The four types you'll use constantly are String, int, double and bool. A fifth, dynamic, switches the checks off for one variable and makes it behave like a JavaScript variable. You will meet it when decoding JSON (first in §04, then for real in §14); avoid it elsewhere.

final is JavaScript's const. Dart's const is stronger.

This is the difference JavaScript developers trip over most:

  • final means "assigned exactly once". The value can be worked out while the app runs, and if it is a list or an object, its contents can still change. That is precisely what const means in JavaScript.
  • const means "known completely when the code is compiled, and frozen all the way down". A const list can never change.
final_vs_const.dart
void finalVsConst() {
  final cart = [1, 2];
  cart.add(3); // fine: final stops reassignment, the list itself can change

  const sizes = [1, 2];
  sizes.add(3); // throws at run time: a const list can never change
}

The last line compiles, and throws when it runs: Unsupported operation: Cannot add to an unmodifiable list. You will write const a great deal in Flutter, in front of widgets. §06 and §09 explain what it buys you there.

Null safety

In JavaScript any variable may turn out to be null or undefined, and you find out when the app crashes with "cannot read properties of undefined". Dart has sound null safety: a variable can only be null if its type ends in a question mark, and the compiler makes you deal with that before you use the value.

String? nickname; // may hold a String or null; starts as null

int nicknameLength() {
  // return nickname.length;   ← compile error: nickname might be null
  return nickname?.length ?? 0; // ?. and ?? work the way they do in JS
}

String shout(String? input) {
  if (input == null) return '';
  return input.toUpperCase(); // promoted: after the check, input is a String
}

Look at shout. After if (input == null) return ''; the compiler knows that input cannot be null on the lines below, so it lets you call toUpperCase() on it. This is type promotion, and it removes most of the ceremony from null safety.

Promotion works on local variables and parameters. It does not work on a global like nickname, because other code could change it between your check and your use. That is why nicknameLength uses ?. instead of an if. The same goes for the fields of a class (classes are the next section). The way around it is to copy the value into a local variable first and check that.

Two escape hatches: ! and late

escape_hatches.dart
int mustHaveLength(String? input) {
  return input!.length; // "trust me, it isn't null". Throws if it is.
}

input! tells the compiler "I know this isn't null". If you are wrong, the app throws Null check operator used on a null value at that line. Every ! is a place where the compiler stopped protecting you, so use it only when you can see why the value is there.

late.dart
class Session {
  late final String token; // "I will set this before anyone reads it"

  void start() {
    token = 'abc123';
  }
}

This one uses a class, which the next section explains; read token as a variable that belongs to a Session object. late postpones the check: the variable has a non-nullable type but is assigned later, after the object is created. Read it too early and you get LateInitializationError: Field 'token' has not been initialized. In Flutter you'll use late final for objects created in initState (§08).

Functions

int add(int a, int b) {
  return a + b;
}

int triple(int n) => n * 3; // arrow form: one expression, returned

// Named parameters go inside { }. The caller writes the name.
String greet(String name, {String greeting = 'Hello', bool loud = false}) {
  final text = '$greeting, $name';
  return loud ? text.toUpperCase() : text;
}

// required: a named parameter the caller may not leave out.
double area({required double width, required double height}) => width * height;

// Optional positional parameters go inside [ ].
String initials(String first, [String? last]) =>
    last == null ? first[0] : '${first[0]}${last[0]}';

And this is how they are called (these lines go in the same file as the functions, or in a file that imports it; §04 explains imports):

the same file, further down
final g1 = greet('Ada'); // 'Hello, Ada'
final g2 = greet('Ada', greeting: 'Hi', loud: true); // 'HI, ADA'
final roomArea = area(width: 3, height: 2); // 6.0
final short = initials('Ada', 'Lovelace'); // 'AL'

Functions are values, as in JavaScript, and they are closures. An anonymous function is written without the function keyword:

closures.dart
final doubled = [1, 2, 3].map((n) => n * 2).toList(); // [2, 4, 6]

final evens = [1, 2, 3, 4].where((n) {
  final isEven = n % 2 == 0; // a body with { } needs an explicit return
  return isEven;
}).toList(); // [2, 4]

Strings and numbers

strings_numbers.dart
final user = 'Ada';
final hello = 'Hello, $user!'; // 'Hello, Ada!'
final info = '${user.length} letters, ${user.toUpperCase()}'; // 3 letters, ADA
final half = 7 / 2; // 3.5  (/ always gives a double)
final whole = 7 ~/ 2; // 3    (~/ divides and drops the remainder)
final parsed = int.parse('42') + 1; // 43
// final oops = '42' + 1;   ← compile error: Dart never converts types for you
  • $name inserts a variable. Anything more than a plain name needs braces: ${user.length}.
  • Dart never converts between types for you. '42' + 1 is rejected at compile time (The argument type 'int' can't be assigned to the parameter type 'String'.) where JavaScript would give you "421". Convert on purpose with int.parse('42'), double.parse(…) or value.toString().
  • / always produces a double, even for 6 / 2. Use ~/ when you want a whole number.
  • == compares values the way you'd expect for numbers, strings and booleans. For objects it is more interesting; that is the last part of §05.
Foundations§04

Dart for JavaScript developers, part 2: classes, files, collections, async

In one sentenceFlutter code is classes all the way down. Once you can read a Dart class, an import line, a list with an if inside it and an await, you can read almost any widget.

Classes, in three steps

React moved from classes to functions. Flutter did not: every widget is a class. Start with the smallest one.

class Todo {
  Todo(this.id, this.title); // the constructor: it has the class's name

  final int id; // fields are declared here, with their types
  final String title;
}

final todo = Todo(1, 'Buy milk'); // create one: no `new` keyword
final text = todo.title; // 'Buy milk'
  • Fields are declared in the class body with their types. A final field is set once, by the constructor, and never again.
  • The constructor has the class's name. There is no constructor keyword. this.id in its parameter list means "take this argument and store it in the field id".
  • There is no new. You create an object by calling the constructor.

Step two adds what every Flutter widget uses: named parameters, a const constructor and a getter.

step 2
class Todo {
  // Named parameters (§03), each stored straight into a field.
  const Todo({required this.id, required this.title, this.done = false});

  final int id;
  final String title;
  final bool done;

  // A getter: read like a field, computed when asked.
  String get label => done ? '✓ $title' : title;
}

const todo = Todo(id: 1, title: 'Buy milk');
final label = todo.label; // 'Buy milk'
// todo.done = true;   ← compile error: done is final
  • {required this.id, …, this.done = false} are the named parameters from §03, each stored into a field. This is exactly the shape of a widget's constructor.
  • const in front of the constructor allows callers to create compile-time constant objects (const Todo(…)), as long as every field is final.
  • String get label => … is read as todo.label, without parentheses.

Step three, the complete class with JSON support, comes after maps, a little further down.

extends, implements, with

shapes.dart
abstract class Shape {
  double get area; // no body: every subclass must provide it
}

class Circle extends Shape {
  Circle(this.radius);
  final double radius;

  @override
  double get area => 3.14159 * radius * radius;
}

// A mixin is a bundle of members that any class can add with `with`.
mixin Describable {
  String describe() => 'I am a $runtimeType';
}

class Square extends Shape with Describable {
  Square(this.side);
  final double side;

  @override
  double get area => side * side;
}

What each keyword does:

  • extends is Inheritance, as in JavaScript: one parent class. An abstract class cannot be created itself; it exists to be extended. @override marks a member that replaces the parent's.
  • implements means "I promise to have all of that class's methods and fields, but I inherit none of its code". Any ordinary class can be used as an interface this way (a class marked final, base or sealed cannot, outside its own file). You'll mostly see it in tests, for fakes.
  • with adds a mixin: a bundle of members that is not a parent. You'll write with SingleTickerProviderStateMixin to give a class the ability to drive animations (§08).

runtimeType, used in describe(), exists on every Dart object: it is the class the object actually is. Flutter relies on it to tell widgets apart (§09).

A subclass that has to pass arguments to its parent's constructor does it after a colon, or with the super. shorthand:

animals.dart
class Animal {
  Animal(this.name);

  final String name;
}

class Dog extends Animal {
  Dog() : super('dog'); // run the parent's constructor first, with 'dog'
}

class Cat extends Animal {
  Cat(super.name); // shorthand: take a name and pass it straight up
}

In Flutter you extend StatelessWidget, StatefulWidget or State and almost nothing else. Bigger widgets are made by putting widgets inside each other (§06), not by extending them.

static: things that belong to the class

temperature.dart
class Temperature {
  const Temperature(this.celsius);

  final double celsius;

  // static: belongs to the class itself, not to one Temperature object.
  static const freezing = Temperature(0);

  static Temperature fromFahrenheit(double f) => Temperature((f - 32) / 1.8);
}

final cold = Temperature.freezing; // ClassName.member
final body = Temperature.fromFahrenheit(212).celsius; // 100.0

A static field or method belongs to the class, not to one object, and you reach it as ClassName.member. It is the same idea as static in a JavaScript class. This is what you are looking at whenever Flutter code says Colors.teal, Icons.add, EdgeInsets.zero or Theme.of(context): a constant or a function that lives on a class.

Private means "starts with an underscore"

wallet.dart
class Wallet {
  int _cents = 0; // the leading _ makes it private to this file

  int get cents => _cents;

  void deposit(int amount) {
    _cents += amount;
  }
}

Dart has no private keyword. A name that begins with _ is visible only inside its own file. This is a rule of the language, not a naming habit: code in another file cannot reach _cents at all. It applies to classes too, which is why the generated counter app has a class named _MyHomePageState.

Files and imports

An app is many files, and a file sees only what it imports. All your code lives under lib/. Here is one file:

lib/task.dart
class Task {
  const Task({required this.id, required this.title});

  final int id;
  final String title;
}

const _draftId = -1; // starts with _: other files cannot see it

Task draft(String title) => Task(id: _draftId, title: title);

The second file, next to it, uses the first one and four other libraries. One of them is the package http, which a new project does not have yet. Add it first, or the import is an error (Target of URI doesn't exist: 'package:http/http.dart'):

flutter pub add http
lib/task_store.dart
import 'dart:async'; // built into Dart: Timer, Future, Stream
import 'dart:convert' show jsonEncode; // show: only this one name

import 'package:flutter/foundation.dart'; // from a package (here: Flutter)
import 'package:http/http.dart' as http; // as: use it as http.Something

import 'task.dart'; // your own file, next to this one

class TaskStore {
  final List<Task> tasks = [draft('Buy milk')];

  String toJson() => jsonEncode([for (final task in tasks) task.title]);

  Future<void> save(http.Client client, Uri uri) async {
    final response = await client.post(uri, body: toJson());
    debugPrint('saved: ${response.statusCode}');
  }

  // Save once, five seconds from now.
  Timer saveLater(http.Client client, Uri uri) {
    return Timer(const Duration(seconds: 5), () => save(client, uri));
  }
}

There are three kinds of import, and you can tell them apart by how the string starts:

Starts withComes fromExamples
dart:Dart itself. Nothing to install.dart:async (Timer, Future, Stream), dart:convert (JSON), dart:math, dart:isolate
package:A package listed in pubspec.yaml: Flutter, or something you added with flutter pub add.package:material_ui/material_ui.dart, package:http/http.dart
a file name or pathYour own file, relative to this one.'todo.dart', 'screens/login_screen.dart', '../models/todo.dart'

From here on, when a snippet needs an import that is not obvious, the sentence before it says which. The one import almost every Flutter file needs is package:material_ui/material_ui.dart (§02).

Lists, maps and sets

final fruits = <String>['apple', 'pear']; // List<String>, the JS array
final stock = <String, int>{'apple': 3, 'pear': 0}; // Map<String, int>
final tags = <String>{'new', 'sale'}; // Set<String>

final first = fruits[0]; // 'apple'
final pears = stock['pear']; // 0, typed int? because a key can be missing
final kiwis = stock['kiwi']; // null
final inStock = fruits.where((f) => stock[f]! > 0).toList(); // ['apple']

Functions can have a blank too, and then the type argument goes on the call:

first_or.dart
// T is a blank for a type, filled in at each call.
T firstOr<T>(List<T> items, T fallback) {
  return items.isEmpty ? fallback : items.first;
}

final a = firstOr<int>([], 0); // you say what T is … → 0
final b = firstOr(['x', 'y'], '-'); // … or Dart works it out → 'x'

You will rarely write such a function, and you will call them all the time. Navigator.of(context).push<String>(…) means "this call produces a String"; context.watch<Cart>() means "find me the Cart".

if and for inside a list

This is the Dart feature Flutter code leans on most. Inside a list literal you can write if and for directly:

List<String> menu({required bool isAdmin, required List<String> extras}) {
  return [
    'Home',
    if (isAdmin) 'Admin', // included only when the condition is true
    for (final extra in extras) extra.toUpperCase(), // one element per turn
    ...['Settings', 'Help'], // spread, the same as in JS
  ];
}

menu(isAdmin: false, extras: ['beta']) returns ['Home', 'BETA', 'Settings', 'Help']. Dart's for (final x in list) is JavaScript's for (const x of list). An if inside a list may also have an else: if (isAdmin) 'Admin' else 'Sign in',.

In React you write {isAdmin && <AdminLink />} and {items.map(…)} inside JSX. In Flutter a widget's children are a plain list, and you write if (isAdmin) const AdminLink(), and for (final item in items) ItemRow(item), inside it.

The complete Todo class

With maps and type arguments in hand, here is step three: the Todo the rest of this page uses. Save this one as lib/todo.dart; the files in §14 import it.

lib/todo.dart
class Todo {
  // Constructor. `this.id` means "take the argument and store it in the field id".
  const Todo({required this.id, required this.title, this.done = false});

  // A named constructor: a second way to build a Todo.
  Todo.fromJson(Map<String, dynamic> json)
    : id = json['id'] as int,
      title = json['title'] as String,
      done = json['completed'] as bool;

  final int id;
  final String title;
  final bool done;

  // A getter: read like a field, computed when asked.
  String get label => done ? '✓ $title' : title;

  // The fields are final, so "changing" a Todo means making a changed copy.
  Todo copyWith({String? title, bool? done}) =>
      Todo(id: id, title: title ?? this.title, done: done ?? this.done);
}

Using it:

lib/todo.dart, the same file, further down
const todo = Todo(id: 1, title: 'Buy milk'); // no `new` keyword in Dart
final finished = todo.copyWith(done: true);
final label = finished.label; // '✓ Buy milk'
// todo.done = true;   ← compile error: done is final

async, await and Future

A Future is Dart's Promise, and async/await work the way they do in JavaScript. If those are new to you, Async / Await explains them from the ground up.

Future<String> fetchGreeting() async {
  await Future.delayed(const Duration(milliseconds: 100)); // a timer
  return 'hello';
}

Future<void> run() async {
  debugPrint('1');
  final greeting = await fetchGreeting(); // pauses run(), not the app
  debugPrint('2 $greeting');
}

The differences are small. The return type says what the Future will produce: Future<String>, or Future<void> for "nothing, but you can wait for me". And async goes after the parameter list, not before the function.

Throwing and catching errors

average.dart
double average(List<int> numbers) {
  // assert: checked in debug mode only, removed from release builds.
  assert(numbers.length < 1000000, 'that is a lot of numbers');
  if (numbers.isEmpty) {
    throw ArgumentError('numbers must not be empty'); // like `throw new Error`
  }
  return numbers.reduce((a, b) => a + b) / numbers.length;
}

String safeAverage(List<int> numbers) {
  try {
    return 'average: ${average(numbers)}';
  } on ArgumentError catch (error) {
    return 'bad input: ${error.message}'; // only this type of error
  } catch (error) {
    return 'failed: $error'; // anything else
  }
}
  • throw works as in JavaScript, without new. You can throw any object; by convention it is an Exception or one of the ready-made error classes such as ArgumentError and FormatException.
  • try / catch (error) is the same too. The addition is on SomeType catch (error), which catches only that type. Use it when you can handle one kind of failure and want the rest to travel on. When you don't need the error object itself, leave the catch part out: on FormatException { … }.
  • The type of error in a plain catch is Object, the type every Dart value has. Object? means "any value, or null"; you will see it on fields that hold "the last error, if there was one".
  • assert(condition, 'message') is a check for programmer mistakes. It runs in debug mode and is removed from release builds, so never put work that must happen inside it. Flutter itself is full of them; many of the red error screens you will see are a failed assert.
  • An error thrown inside an async function travels through the Future and is caught by a try around the await, as in JavaScript.

Enums, and the dot shorthand

status.dart
enum Status { active, paused }

Status current = Status.active; // the full name
Status next = .paused; // dot shorthand: Dart knows a Status goes here

An enum is a type with a fixed set of values. Flutter uses them for nearly every option: MainAxisAlignment.center, TextAlign.right, BoxFit.cover. Since Dart 3.10 you may drop the type name where Dart already knows it and write .center. The code flutter create generates does that. Both forms compile to the same thing; this page keeps the long one.

Practitioner§05

Dart you will meet later: streams, records, patterns, equality

In one sentenceFour newer or less obvious parts of Dart that show up in other people's Flutter code. You mainly need to be able to read them.

Stream: many values over time

A Future delivers one value. A Stream delivers many: a countdown, messages from a WebSocket, a document that keeps changing in a database. You consume one with await for, or hand it to a widget that rebuilds for every value (§14).

countdown.dart
Stream<int> countdown(int from) async* {
  for (var i = from; i > 0; i--) {
    await Future.delayed(const Duration(seconds: 1));
    yield i; // hand out one value, then keep going
  }
}

Future<void> listen() async {
  await for (final n in countdown(3)) {
    debugPrint('$n'); // 3, then 2, then 1, one second apart
  }
}

async* and yield make a function that produces a stream, the way function* and yield make a generator in JavaScript. You will consume streams far more often than you write them.

Records: a few values in parentheses

A record bundles a few values without a class. Use it to return two things from a function:

records.dart
(int, int) minMax(List<int> numbers) {
  var low = numbers.first;
  var high = numbers.first;
  for (final n in numbers) {
    if (n < low) low = n;
    if (n > high) high = n;
  }
  return (low, high); // a record: two values, no class needed
}

String summary() {
  final (lowest, highest) = minMax([3, 9, 4]); // unpack into two variables
  final person = (name: 'Ada', age: 36); // a record with named fields
  return '$lowest to $highest, ${person.name} is ${person.age}'; // 3 to 9, Ada is 36
}

final (lowest, highest) = … is destructuring, like const [lowest, highest] = minMax(…) in JavaScript. Records arrived in Dart 3.0.

switch as an expression, and patterns

how_many.dart
String howMany(int n) => switch (n) {
  0 => 'none',
  1 => 'one',
  _ => 'many', // _ matches anything: the "everything else" line
};

This switch is an expression: it produces a value, here the String the function returns. There is no case and no break; each line is pattern => result. _ is the wildcard that matches whatever is left.

The patterns can do more than compare with a constant. Together with a sealed class they are how Dart models "one of these few shapes", for example the three states of a screen that loads data:

load_state.dart
sealed class LoadState {}

class Loading extends LoadState {}

class Loaded extends LoadState {
  Loaded(this.items);
  final List<String> items;
}

class Failed extends LoadState {
  Failed(this.message);
  final String message;
}

String describe(LoadState state) => switch (state) {
  Loading() => 'Loading…',
  Loaded(items: []) => 'Nothing here yet',
  Loaded(:final items) => '${items.length} items',
  Failed(:final message) => 'Error: $message',
};

Patterns also work in an if: if (json case [{'title': final String title}, ...]) reads "if json is a list whose first item is a map with a String under 'title', call that String title". You will see this in code that picks decoded JSON apart.

What == means for objects

JavaScript has == and ===. Dart has one ==, and what it does depends on the class. (Circle is the class from §04; Money is defined just below.)

equality.dart
final sameList = [1, 2] == [1, 2]; // false: two different list objects
final sameConst = identical(const [1], const [1]); // true: one shared object
final sameText = 'flutter' == 'FLUTTER'.toLowerCase(); // true: by content
final sameRecord = (1, 'a') == (1, 'a'); // true: field by field
final sameCircle = Circle(1) == Circle(1); // false: no == defined, so identity
final sameMoney = Money(500) == Money(500); // true: Money defines ==
  • For numbers, strings, booleans and records, == compares content.
  • For lists, maps and ordinary objects, == asks "is this the same object?", like === on objects in JavaScript. [1, 2] == [1, 2] is false.
  • identical(a, b) always asks "same object?".
  • Two equal const values are the same object, because the compiler creates each distinct constant once. This is the property Flutter uses to skip rebuilding const widgets (§09).

A class can say what == means for its objects by defining a method named operator ==. If it does, it must define hashCode to match, so that equal objects land in the same place in a Map or Set:

money.dart
class Money {
  Money(this.cents);
  final int cents;

  @override
  bool operator ==(Object other) => other is Money && other.cents == cents;

  @override
  int get hashCode => cents.hashCode;
}

Object is the type every Dart value has, so Object other means "anything". other is Money checks the type, like instanceof in JavaScript, and after it Dart treats other as a Money.

Foundations§06

Everything is a widget

In one sentenceA widget is a small immutable object that describes a piece of UI. Its build method returns more widgets. An app is one big tree of them.

If you know React, you already have the model: a widget class is a component, the object you create from it is an element, and build is the render function. The syntax is the only new part, because Dart has no JSX. You nest constructor calls instead of tags.

The smallest app

The first line is the material_ui import from §02. If your project still says package:flutter/material.dart there, do the switch described at the end of §02 first, and never use both in one project.

import 'package:material_ui/material_ui.dart';

void main() {
  runApp(const HelloApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
      ),
      home: Scaffold(
        appBar: AppBar(title: const Text('Hello')),
        body: const Center(child: Text('Hello, Flutter')),
      ),
    );
  }
}

To run it, replace the contents of lib/main.dart with this code and press R. Then delete test/widget_test.dart: that generated test looks for the counter app's MyApp class, which is now gone, and flutter analyze would report The name 'MyApp' isn't a class. You will write your own tests in §16.

What the five widgets in that tree do:

WidgetJob
MaterialAppThe root of a Material app. Sets up the theme, navigation between screens, text direction and more. You have exactly one.
ThemeDataColours and text styles for everything below. ColorScheme.fromSeed derives a whole palette from one colour. Material 3 is the default look.
ScaffoldThe layout of one screen: a slot for the app bar, a slot for the body, and optional slots for a floating button, drawer and bottom bar.
AppBarThe bar at the top with a title and, on inner screens, a back arrow.
Center, TextCenter centres its one child. Text draws a string.

Names with a dot in them are the static members and named constructors from §04: Colors.teal is a constant on the class Colors, Icons.person one on Icons, and ColorScheme.fromSeed(…), EdgeInsets.all(16) and Image.network(…) are named constructors. When you meet an unfamiliar Something.name, that is how to read it.

Your own widget

A widget's inputs are constructor parameters stored in final fields. They play the role of React Props.

class ProfileCard extends StatelessWidget {
  const ProfileCard({super.key, required this.name, this.role = 'Member'});

  final String name;
  final String role;

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            const Icon(Icons.person, size: 40),
            const SizedBox(width: 12),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(name, style: const TextStyle(fontWeight: FontWeight.bold)),
                Text(role),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

And you use it like any built-in widget:

team_screen.dart (inside a build method)
return const Column(
  children: [
    ProfileCard(name: 'Ada Lovelace', role: 'Engineer'),
    ProfileCard(name: 'Grace Hopper'), // role falls back to 'Member'
  ],
);

Compare the two versions of ProfileCard and one difference stands out. In the React version, padding and layout are style properties on a div. In Flutter there is no style object for layout. Padding, a row and a gap (SizedBox(width: 12)) are all widgets. You get a layout by wrapping widgets in other widgets. This is composition, and it is why Flutter trees look deep. §07 covers these layout widgets one by one.

Two parameter names appear everywhere:

  • child: the widget takes exactly one widget inside it (Padding, Center, Card).
  • children: the widget takes a list (Row, Column, ListView). It is an ordinary Dart list, so the if and for from §04 work inside it.

Buttons, and passing functions

save_bar.dart
class SaveBar extends StatelessWidget {
  const SaveBar({super.key, required this.onSave, this.onDelete});

  final VoidCallback onSave; // a function that takes nothing, returns nothing
  final VoidCallback? onDelete; // may be null

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        FilledButton(onPressed: onSave, child: const Text('Save')),
        TextButton(
          onPressed: () => debugPrint('cancelled'),
          child: const Text('Cancel'),
        ),
        // onPressed: null is how you disable a button.
        IconButton(onPressed: onDelete, icon: const Icon(Icons.delete)),
      ],
    );
  }
}
  • A handler is a function passed as a parameter, like onClick in React. Its type is a function type, written void Function(): "a function with no parameters that returns nothing". VoidCallback is a ready-made name for exactly that type. You will also see void Function(String) (takes a String) and Future<void> Function() (takes nothing, returns a Future).
  • You can pass a function by name (onPressed: onSave) or write one in place (onPressed: () => debugPrint('cancelled')).
  • A button whose onPressed is null is disabled. There is no separate disabled flag. Here the delete button is greyed out whenever the parent doesn't pass onDelete.

const widgets

You have seen const in front of many widgets. It is the const from §03: the object is created once, when the app is compiled, and can never change. A widget can be const when its constructor is const and every argument is a constant too. const Text('Hello') qualifies; Text(name) does not, because name is only known at run time.

const_widgets.dart
Widget greeting() => const Text('Hi');

bool sameWidget() {
  final first = greeting();
  final second = greeting();
  return identical(first, second); // true: both calls return one shared object
}

Every call to greeting() returns the same object. Flutter uses that. To rebuild a part of the screen, it calls the build methods there again and compares the new widgets with the old ones. When it finds the same widget object as last time, it knows nothing below it can have changed, and skips that whole part of the tree. §09 shows this happening.

So the habit is: write const wherever the compiler allows it. One const in front of a parent covers everything inside it, which is why you see const Center(child: Text('Hello, Flutter')) and not two consts. The default lint set does not insist on it. You can ask it to, by adding one rule to analysis_options.yaml:

analysis_options.yaml
include: package:flutter_lints/flutter.yaml

linter:
  rules:
    prefer_const_constructors: true

A widget is a description, not the thing on screen

Creating a Text widget does not draw anything. It creates a small object that says "there should be this text, in this style". Flutter reads the tree of descriptions and keeps its own, longer-lived objects that do the measuring and painting (§09).

This has the same consequence as in React. You never reach into the screen to change a label. You change some data and describe the whole UI again; the framework works out what actually has to change on screen. Building is designed to be cheap, so build methods run often, and they must only describe: no network calls, no timers, no changing of fields inside build.

The widgets you'll use every day

catalogue.dart
class Catalogue extends StatelessWidget {
  const Catalogue({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const Text('Plain text'),
        const Icon(Icons.favorite, color: Colors.pink),
        Image.network('https://example.com/cat.png', width: 80),
        ElevatedButton(onPressed: () {}, child: const Text('Elevated')),
        OutlinedButton(onPressed: () {}, child: const Text('Outlined')),
        const Divider(),
        const ListTile(
          leading: Icon(Icons.mail),
          title: Text('Inbox'),
          subtitle: Text('3 unread'),
          trailing: Icon(Icons.chevron_right),
        ),
        const CircularProgressIndicator(),
      ],
    );
  }
}
NeedWidgets
Text and picturesText, Icon(Icons.…), Image.network(url), Image.asset(path) (§19)
ButtonsFilledButton (the main action), ElevatedButton, OutlinedButton, TextButton, IconButton, FloatingActionButton
One row of a listListTile (leading icon, title, subtitle, trailing icon, onTap)
GroupingCard, Divider
WaitingCircularProgressIndicator, LinearProgressIndicator
Screen structureScaffold, AppBar, Drawer (§10), NavigationBar (§13)
LayoutRow, Column, Padding, SizedBox, Expanded, Stack, Center (§07)

All of these are drawn by Flutter. FilledButton is a few hundred lines of Dart in the framework that you can open and read from your editor ("go to definition"). Nothing in that list asks iOS or Android to draw a control.

Foundations§07

Layout: constraints go down, sizes go up

In one sentenceConstraints go down. Sizes go up. The parent sets the position. Every size on a Flutter screen, and every layout error, comes out of those three sentences.

In CSS you set width: 100px on an element and usually get 100 pixels. In Flutter you write Container(width: 100) (a Container is a plain box, Flutter's div) and sometimes get a box that fills the whole screen. That is the layout rule at work: a Flutter widget does not decide its own size alone. It picks one inside limits that its parent gives it.

Those limits are called constraints: a minimum and a maximum width, and a minimum and a maximum height. Lengths are in logical pixels, which are about the same physical size on every phone. A typical phone is 360 to 430 logical pixels wide.

Three words describe the constraints a child can get. You will see them in error messages:

  • Tight: minimum equals maximum. "Be exactly this size." The child has no say.
  • Loose: the minimum is 0. "Be any size up to this."
  • Unbounded: the maximum is infinity. "Be as long as you like." Scrolling widgets give this along the direction they scroll in.

Here are the two cases from the top of this section:

constraints.dart
// 1. Straight on the screen. The screen says "be exactly my size",
//    so width: 100 and height: 100 lose. Result: a full-screen red box.
Widget fullScreen() => Container(width: 100, height: 100, color: Colors.red);

// 2. Center says "be any size up to mine" and then centers the child.
//    Result: a 100 × 100 red box in the middle.
Widget centered() =>
    Center(child: Container(width: 100, height: 100, color: Colors.red));

Now try the combinations yourself. Before each click, predict the size of the teal box.

Constraints playground
Pick a parent and a child. The phone is 360 × 640 logical pixels; every number below was checked against real Flutter.
parent
child: a Container
360 × 640
↓ 1. Constraints go down (parent → Container)
width: 0 to 360 (loose)
height: 0 to 640 (loose)
↑ 2. Sizes go up (Container → parent)
asked for 100 × 100, is 100 × 100
⌖ 3. Parent sets position
x 130, y 270 (from the top left of the screen)
The parent only sets an upper limit, so the child may be any size up to it.
what build returns
return Center(child: Container(width: 100, height: 100, color: Colors.teal));

Four things to take away from the playground:

  • The parent wins. A child's width and height are wishes. They are honoured only if they fit inside the constraints.
  • To make a child smaller than its parent, put something between them that loosens the constraints: Center, Align, a Row or a Column.
  • A widget with nothing in it and no size collapses to zero on an unbounded axis. If a Container or a SizedBox "isn't showing", check for a height of 0.
  • A vertical list forces its children to its own width. ListView (the scrolling list, §11) passes each child a tight width, so a child's width is ignored there. Try it in the playground.

Row and Column

A Row lays its children out left to right, a Column top to bottom. They are Flutter's Flexbox. If you have read CSS Layout → Flexbox you know the ideas already; only the names differ.

  • The main axis is the direction the children are laid out in: horizontal for a Row, vertical for a Column.
  • The cross axis is the other one.
CSS FlexboxFlutterNotes
display: flex; flex-direction: rowRow(children: […])Column for column
justify-contentmainAxisAlignmentstart, center, end, spaceBetween, spaceAround, spaceEvenly
align-itemscrossAxisAlignmentstart, center, end, stretch. The default is center, not stretch
flex: 1Expanded(child: …)Expanded(flex: 2, …) for two shares
gap: 12pxspacing: 12or a SizedBox(width: 12) between two children
flex-wrap: wrapuse a Wrap widgeta Row never wraps
flex-shrink(nothing)children are never squeezed; they overflow
(the container's own size)mainAxisSizemax (fill the main axis, the default) or min (hug the children)
Row / Column playground
Three boxes in a 320 × 240 area. The dashed outline is the Row or Column itself.
widget
mainAxisAlignment
crossAxisAlignment
mainAxisSize
child B
child A
━━▶ main axis: horizontal┃ cross axis: vertical
A
B
C
Row: 320 × 70A: 60 × 40 at (0, 15)B: 90 × 70 at (60, 0)C: 50 × 50 at (150, 10)
The Row takes the full 320 along its main axis. The children use 200; MainAxisAlignment.start decides where the other 120 go. Across, the Row is only as tall as it needs to be (70).
the widget tree for these settings
return Row(
  mainAxisAlignment: MainAxisAlignment.start,
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisSize: MainAxisSize.max,
  children: [
    SizedBox(width: 60, height: 40), // A
    SizedBox(width: 90, height: 70), // B
    SizedBox(width: 50, height: 50), // C
  ],
);

The flex-shrink row is where CSS habits lead you astray, so here it is in words. A CSS flex container shrinks its items when space runs out. A Flutter Row never shrinks a child. It lets each plain child be as wide as it wants, and if the total is too much, the children stick out past the edge. That is the overflow error, and Expanded is the usual cure.

Expanded, Flexible and Spacer

How a Row or Column shares out its main axis, in order:

  1. Each child that is not wrapped in Expanded or Flexible is asked "how long do you want to be?", with no upper limit, and gets that length.
  2. What is left over is divided among the Expanded and Flexible children, in proportion to their flex factor (1 unless you say otherwise).
message_row.dart
class MessageRow extends StatelessWidget {
  const MessageRow({super.key, required this.text});

  final String text;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        const CircleAvatar(child: Icon(Icons.person)),
        const SizedBox(width: 12), // a fixed gap
        Expanded(child: Text(text)), // ← gets the width that is left over
        const Icon(Icons.chevron_right),
      ],
    );
  }
}

CircleAvatar is a round picture or icon, 40 wide by default. On a 360-wide screen the avatar takes 40, the gap 12 and the arrow 24. Expanded hands the remaining 284 to the Text as a tight width, so a long message wraps inside it instead of running off the screen. Step through both passes, then take the Expanded away:

How a Row shares out its width
The message row from the code above, on a 360-wide screen. Step through, then switch Expanded off.
0the Row: 360 wide360
avatargaptextarrow
The screen gives the Row a width of exactly 360. Now the Row has to share that out among four children: an avatar, a gap, the text and an arrow.
step 1 / 3
The widths were measured in a test, which uses a fixed test font. Your text will give other numbers; the two passes stay the same.
  • Expanded forces its child to fill its share exactly.
  • Flexible offers the same share as an upper limit: the child may be smaller.
  • Spacer() is an Expanded with nothing in it. It soaks up empty space.
total_row.dart
class TotalRow extends StatelessWidget {
  const TotalRow({super.key, required this.total});

  final String total;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        const Text('Total'),
        const Spacer(), // an empty Expanded: pushes the total to the far end
        Text(total),
      ],
    );
  }
}
chat_bubble.dart
class ChatBubble extends StatelessWidget {
  const ChatBubble({super.key, required this.text});

  final String text;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        // Flexible: "at most the leftover width". A short message stays
        // narrow; a long one stops at the edge and wraps.
        Flexible(
          child: Container(
            padding: const EdgeInsets.all(12),
            color: Colors.teal.shade100,
            child: Text(text),
          ),
        ),
      ],
    );
  }
}

For an even gap between all the children, Row and Column have a spacing parameter. And when items should flow onto the next line, use Wrap:

rating.dart
class Rating extends StatelessWidget {
  const Rating({super.key});

  @override
  Widget build(BuildContext context) {
    return const Row(
      spacing: 12, // the same gap between every two children, like CSS gap
      children: [Icon(Icons.star), Text('4.8'), Text('(120 reviews)')],
    );
  }
}

A Chip is a small rounded label.

tag_list.dart
class TagList extends StatelessWidget {
  const TagList({super.key, required this.tags});

  final List<String> tags;

  @override
  Widget build(BuildContext context) {
    // Wrap is a Row that starts a new line when it runs out of width.
    return Wrap(
      spacing: 8, // gap between chips on one line
      runSpacing: 8, // gap between lines
      children: [for (final tag in tags) Chip(label: Text(tag))],
    );
  }
}

The overflow error

Take the Expanded out of the message row:

overflow.dart (inside a build method)
return Row(
  children: [
    const CircleAvatar(child: Icon(Icons.person)),
    const SizedBox(width: 12),
    Text(text), // ✗ no Expanded: the Row lets it be as wide as it likes
    const Icon(Icons.chevron_right),
  ],
);

With a long text, a debug build paints yellow and black stripes over the right edge and logs this (the number depends on the text):

A RenderFlex overflowed by 1284 pixels on the right.

RenderFlex is the object that does the layout for both Row and Column, so this message means "the children of a Row or Column need more room than it has". By step 1 above, the Text was asked for its ideal width with no limit and answered with one very long line. The fixes, in the order to try them:

  1. Wrap the child that should give way in Expanded (or Flexible).
  2. If the content is really longer than the screen, make it scroll: ListView, or SingleChildScrollView around a Column (both are in §11).
  3. For a Row of chips or tags, switch to Wrap.

The single-child wrappers

There is no style object. Each of these adds one layout behaviour to the widget inside it. (Placeholder, used below, draws a box with a cross through it: a stand-in for content you have not built yet.)

wrappers.dart
class Wrappers extends StatelessWidget {
  const Wrappers({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Padding: space inside, around the child.
        const Padding(padding: EdgeInsets.all(16), child: Text('Padded')),
        // SizedBox: a fixed size, or a gap when it has no child.
        const SizedBox(height: 24),
        const SizedBox(width: 120, height: 40, child: Placeholder()),
        // Container: padding, margin, size and decoration in one widget.
        Container(
          margin: const EdgeInsets.symmetric(vertical: 8),
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: Colors.amber.shade100,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.amber),
          ),
          child: const Text('Decorated'),
        ),
        // Align: place the child inside the space Align itself takes.
        const Align(alignment: Alignment.centerRight, child: Text('Right')),
      ],
    );
  }
}
WidgetWhat it doesCSS you know
PaddingSpace around its child, inside itselfpadding
SizedBoxForces a width and/or height; with no child, an empty gapwidth / height
Center, AlignTakes all the space it is offered and places the child inside itplace-items: center
ContainerA convenience widget: padding + margin + size + colour/border/radius in onea styled div
ConstrainedBoxAdds extra limits, such as a maximum widthmax-width
AspectRatioSizes the child to a width-to-height ratioaspect-ratio

Stack: things on top of each other

Row and Column put children next to each other. Stack puts them on top of each other, first child at the bottom, like position: absolute children inside a position: relative parent (CSS Layout → Positioning).

avatar_badge.dart
class AvatarWithBadge extends StatelessWidget {
  const AvatarWithBadge({super.key});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        const CircleAvatar(radius: 28, child: Icon(Icons.person)),
        Positioned(
          right: 0,
          top: 0,
          child: Container(
            width: 14,
            height: 14,
            decoration: const BoxDecoration(
              color: Colors.green,
              shape: BoxShape.circle,
            ),
          ),
        ),
      ],
    );
  }
}

A Positioned child is pinned by top, right, bottom and left distances from the Stack's edges. Children that are not wrapped in Positioned sit at the top left (change that with the Stack's alignment) and decide how big the Stack itself is.

SafeArea: notches and home indicators

Phones have a status bar, a camera cutout, rounded corners and a home indicator. The part of the screen that is free of all of them is the safe area.

screen.dart
class Screen extends StatelessWidget {
  const Screen({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: SafeArea(child: Text('Never hidden behind the notch')),
    );
  }
}

A Scaffold with an AppBar already keeps the bar clear of the status bar. Add SafeArea around the body of screens without an app bar, and around anything that sits at the very bottom.

The two "unbounded" errors, explained by constraints

Both of these come up in everyone's first week. Both follow directly from the rule.

1. A ListView inside a Column.

broken_inbox.dart (inside a build method)
return Column(
  children: [
    const Text('Inbox'),
    ListView(children: const [Text('one'), Text('two')]), // ✗ throws
  ],
);
Vertical viewport was given unbounded height.

A viewport is the window of a scrolling widget, so this message is about the ListView. A Column asks each plain child "how tall do you want to be?" with no upper limit. A ListView answers "as tall as you'll let me": it wants to fill its parent and scroll inside. As tall as infinity is not a size, so Flutter stops. The fix gives the list a real height by letting it take what is left:

fixed_inbox.dart (inside a build method)
return Column(
  children: [
    const Text('Inbox'),
    Expanded(
      // ✓ Expanded hands the ListView a fixed height: whatever is left
      child: ListView(children: const [Text('one'), Text('two')]),
    ),
  ],
);

2. An Expanded inside something that scrolls.

broken_form.dart (inside a build method)
return const SingleChildScrollView(
  child: Column(
    children: [
      Text('Sign up'),
      Expanded(child: Placeholder()), // ✗ "the rest" of an endless height
    ],
  ),
);
RenderFlex children have non-zero flex but incoming height constraints are unbounded.

SingleChildScrollView lets its child be endlessly tall, because that is what scrolling means. Inside it, Expanded asks for "the rest of the height". There is no "rest" of an endless height. Drop the Expanded and give that child a fixed height, or decide that this screen does not scroll.

Adapting to the screen

Two tools, for two different questions:

  • "How wide is the space I was given?" Use LayoutBuilder. It hands you the constraints from the parent, so it works for a widget in a sidebar as well as for a full screen.
  • "How big is the whole screen?" Use MediaQuery.sizeOf(context) (§10).
responsive.dart
class Responsive extends StatelessWidget {
  const Responsive({super.key});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        // constraints is what the parent passed down to this spot.
        if (constraints.maxWidth >= 600) {
          return const Row(children: [Text('Sidebar'), Text('Content')]);
        }
        return const Column(children: [Text('Content')]);
      },
    );
  }
}

LayoutBuilder is Flutter's answer to a CSS container query: it responds to the parent's size, not the window's.

It is also the first builder on this page: a function you pass to a widget, which returns a widget, and which Flutter calls when it needs that part. You will see the same shape in lists (itemBuilder), routes and async widgets.

Practitioner§08

State: StatefulWidget, setState and the lifecycle

In one sentenceA widget is thrown away and recreated on every rebuild, so it cannot remember anything. Memory lives in a separate, long-lived State object. You change its fields inside setState, and Flutter rebuilds.

A counter, in both worlds

class Counter extends StatefulWidget {
  const Counter({super.key, this.step = 1});

  final int step; // configuration from the parent, like a prop

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0; // state: lives in this object, survives rebuilds

  void _increment() {
    setState(() {
      _count += widget.step; // ← change fields inside setState
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('Count: $_count'),
        FilledButton(onPressed: _increment, child: const Text('Add')),
      ],
    );
  }
}

React keeps the state for you behind useState. Flutter makes the two halves explicit, as two classes:

  • Counter is the widget: the immutable configuration that the parent passes down. Its only job besides holding step is to create the State.
  • _CounterState is the State: an ordinary object with ordinary fields (_count) and the build method. Flutter creates it once and keeps it for as long as a Counter stays at that spot in the tree.

What setState does

setState is the one way a State tells Flutter that it changed.

setState(() { _count += widget.step; }) does two things, in this order:

  1. It runs the function you gave it, immediately. _count has its new value before setState returns.
  2. It marks this State as needing a rebuild and asks Flutter for a new Frame. Just before that frame is drawn, Flutter calls build() again.

So the State's fields are plain mutable variables. There is nothing like React's "each render sees its own snapshot": inside one _CounterState there is one _count, and it always holds the latest value. The function passed to setState exists to make you put the change and the "please rebuild" in the same place. Change a field outside setState and the value changes but the screen does not.

React useStateFlutter setState
Where the value livesIn React, handed to you each renderIn a field of your State object
Reading it right after settingStill the old value in this renderAlready the new value
Calls in one handlerBatched into one renderEach call marks the same State; one rebuild next frame
Needs an updater function for "old + 1"?Yes (c => c + 1), because of snapshotsNo. _count++ is always right
Mutating a list in stateDoes not re-renderWorks, if you do it inside setState

The lifecycle

React function components have one lifecycle tool, useEffect. A State object has named methods that Flutter calls at fixed moments. Step through one State's whole life. The widget is called Probe: a button that shows its label and its own tap count, in the theme's colour. The logs are from a test that ran these exact steps:

The life of one State object
One widget at one spot in the tree: created, rebuilt three different ways, removed.
What the parent's build returns
Probe(label: 'A')
The State object
not created yet
Flutter calls, in order
—
A parent's build returns a Probe(label: 'A') widget for the first time. There is nothing at this spot in the tree yet, so Flutter creates a new element for it and calls createState() to get the State object. Each step below is from a real run; the log is what the test recorded.
1 / 8

What belongs where:

MethodCalledPut hereReact equivalent
initState()Once, when the State is createdCreate controllers, start timers, start listening to things, kick off the first loaduseEffect(…, []) setup
didChangeDependencies()After initState, and when inherited data this State reads changes (§10)Rarely needed: work that depends on Theme.of(context) or similar and is too heavy for build—
build()Whenever this State may look differentOnly describe the UIthe function body
didUpdateWidget(old)When the parent rebuilds with a new widget for this StateReact to a changed parameter: restart something if widget.id != old.idan effect with [id] in its dependency array
deactivate()When the State is taken out of the tree, just before disposeAlmost never overridden—
dispose()Once, when the State is removed for goodCancel timers, stop listening, dispose controllersthe cleanup function an effect returns

initState itself cannot be marked async. To load data when a screen opens, write an async method and call it from initState without await; §11 and §14 do exactly that.

Here is a widget that needs three of them. Timer comes from dart:async, so the file starts with import 'dart:async';:

elapsed_time.dart
class ElapsedTime extends StatefulWidget {
  const ElapsedTime({super.key, this.label = 'Elapsed'});

  final String label;

  @override
  State<ElapsedTime> createState() => _ElapsedTimeState();
}

class _ElapsedTimeState extends State<ElapsedTime> {
  late final Timer _timer;
  int _seconds = 0;

  @override
  void initState() {
    super.initState(); // always first
    // Runs once, when this State object is created. Start things here.
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      setState(() => _seconds++);
    });
  }

  @override
  void didUpdateWidget(ElapsedTime oldWidget) {
    super.didUpdateWidget(oldWidget);
    // The parent rebuilt and handed this State a new ElapsedTime widget.
    // `widget` is already the new one. Compare it with oldWidget if you
    // have to react to a changed parameter.
    if (widget.label != oldWidget.label) {
      // No setState needed: Flutter always calls build right after this.
      _seconds = 0; // a different label: start counting again
    }
  }

  @override
  void dispose() {
    // Runs once, when this State is removed for good. Stop things here.
    _timer.cancel();
    super.dispose(); // always last
  }

  @override
  Widget build(BuildContext context) {
    return Text('${widget.label}: $_seconds s');
  }
}

Controllers: state you can hold in your hand

Some built-in widgets keep their state in an object that you create and pass in, called a controller. A text field's text and cursor live in a TextEditingController. A scroll view's position lives in a ScrollController. With the controller in hand you can read and change that state from outside the widget.

search_box.dart
class SearchBox extends StatefulWidget {
  const SearchBox({super.key, required this.onSearch});

  final ValueChanged<String> onSearch; // a function that takes one String

  @override
  State<SearchBox> createState() => _SearchBoxState();
}

class _SearchBoxState extends State<SearchBox> {
  final _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose(); // you created it, so you dispose it
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(child: TextField(controller: _controller)),
        IconButton(
          icon: const Icon(Icons.search),
          onPressed: () => widget.onSearch(_controller.text),
        ),
        IconButton(
          icon: const Icon(Icons.clear),
          onPressed: _controller.clear, // the controller can also write
        ),
      ],
    );
  }
}

(The TextField sits in an Expanded because a text field in a Row must be told how wide it may be; §21, pitfall 16.)

The rule for all controllers: the State that creates one disposes it. Create it as a field (or in initState), call .dispose() on it in dispose(). A StatelessWidget has no dispose, which is why a widget that owns a controller has to be stateful.

AnimationController

An animation is a number that changes a little on every frame. AnimationController produces that number, from 0.0 to 1.0 over a duration.

pulse.dart
class Pulse extends StatefulWidget {
  const Pulse({super.key, required this.child});

  final Widget child;

  @override
  State<Pulse> createState() => _PulseState();
}

class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this, // lets the controller tick once per frame
      duration: const Duration(seconds: 1),
    )..repeat(reverse: true);
  }

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

  @override
  Widget build(BuildContext context) {
    // _controller.value runs 0 → 1 → 0 …; FadeTransition repaints on each tick.
    return FadeTransition(opacity: _controller, child: widget.child);
  }
}

For simple cases you don't need a controller at all. Widgets whose names start with Animated (AnimatedContainer, AnimatedOpacity, AnimatedAlign) animate by themselves whenever you rebuild them with a new value.

After an await, the State may be gone

A handler starts a save, the user presses back, and two seconds later the save finishes. The State has been disposed in the meantime. These lines are from a State with a bool _saving field, whose widget has a save function as a parameter:

saver.dart (inside a State)
setState(() => _saving = true);
await widget.save(); // the user may leave the screen while this runs
setState(() => _saving = false); // ✗ throws if this State was disposed

In a debug build the last line throws:

setState() called after dispose(): _SaverState#deb99(lifecycle state: defunct, not mounted)

Inside a State you can use context anywhere, not only in build: every State has a context property, which is the same object build receives. That is how the snack bar and navigation calls in later sections work from a handler method.

Every State has a mounted property that is true from before initState until dispose. Check it after every await, before you touch setState or context:

saver.dart (inside a State)
Future<void> _save() async {
  setState(() => _saving = true);
  await widget.save();
  if (!mounted) return; // ✓ the State is gone: nothing left to update
  setState(() => _saving = false);
}

useState and useEffect, translated

You want to…ReactFlutter
Remember a valueuseStatea field in the State + setState
Run once when shownuseEffect(fn, [])initState()
Clean up when removedreturn a function from the effectdispose()
React to a prop changeuseEffect(fn, [prop])didUpdateWidget(old) and compare
Keep a value without re-renderinguseRefa field you change without setState
Reach a child imperativelyrefa controller, or a GlobalKey (§12)
Compute from statecalculate in render (or useMemo)calculate in build (or cache in a field)

The rules of hooks have no Flutter equivalent. A State is an ordinary object, so there is no call order to protect and no dependency array to get wrong. The price is more lines for the same counter.

Practitioner§09

The three trees: widgets, elements, render objects

In one sentencebuild returns throwaway widgets. Flutter keeps two other trees that last: elements, which remember what is where (and hold your State), and render objects, which measure and paint. A rebuild creates new widgets and updates the other two.

Section 08 said Flutter creates a State once and keeps it for as long as its widget "stays at that spot in the tree". This section explains what "that spot" means, because that one idea accounts for state that survives when you expected a reset, state that vanishes when you expected it to stay, and tap counts that end up on the wrong list row.

If you know React's internals, the mapping is close: a widget is a React element, the element tree is React's own tree of component instances, and render objects play the part of DOM nodes. The comparing step is what React calls reconciliation (How React Works → Reconciliation).

One tap, start to finish

One tap, three trees
What setState really causes, from the tap to the new pixels.
Code
1class _CounterState extends State<Counter> {
2 int _count = 0; // state: lives in this object, survives rebuilds
3
4 void _increment() {
5 setState(() {
6 _count += widget.step; // ← change fields inside setState
7 });
8 }
9
10 @override
11 Widget build(BuildContext context) {
12 return Column(
13 mainAxisSize: MainAxisSize.min,
14 children: [
15 Text('Count: $_count'),
16 FilledButton(onPressed: _increment, child: const Text('Add')),
17 ],
18 );
19 }
20}
Widgetsrecreated on every build
Counter
↳ Column
  ↳ Text('Count: 0')
  ↳ FilledButton
    ↳ const Text('Add')
Elementskept
Counter element holds the State: _count = 0
↳ Column element
  ↳ Text element
  ↳ FilledButton element
    ↳ Text element
Render objectskept, updated in place
RenderFlex lays out the column
↳ RenderParagraph “Count: 0”
↳ the button's render objects
  ↳ RenderParagraph “Add”
The first build. build() returns a tree of widgets: small immutable descriptions. For each one Flutter creates an element, the long-lived object that holds that spot in the tree. Widgets that actually draw something also get a render object, which knows its size and how to paint. The Counter has no render object of its own; it only combines other widgets.
1 / 7

Three facts from that walkthrough are worth stating on their own:

  • Calling setState does not rebuild anything by itself. It marks one element as dirty. The rebuild happens once, at the start of the next frame, however many times you called it.
  • A rebuild starts at the dirty element and goes down, never up. The parent of the Counter is not involved.
  • Rebuilding is cheap because the expensive objects are reused. A rebuild allocates a few small widget objects and updates fields on existing render objects.

The matching rule

At each spot Flutter compares the old widget with the new one and asks a single question. The framework function is called Widget.canUpdate, and this is all it checks:

Same runtimeType and same key? Then keep the element (and its State, and its render object) and hand it the new widget. Otherwise throw the old element away, with everything under it, and build the new widget from nothing.

runtimeType is the widget's class. A key is an optional identity you can give a widget; most widgets have none, and "no key" equals "no key". So in everyday code the rule is: same class at the same spot means same State.

Flutter never compares the fields of the two widgets. A Text('a') and a Text('b') match, and so do two Counters with different steps. That is why, in §08's lifecycle walkthrough, the State kept its tap count when the parent swapped Probe(label: 'A') for Probe(label: 'B').

When state survives and you wanted a reset

The State is kept because the type and spot are the same, even if the widget now "means" a different thing: a form that was showing user 1 and now shows user 2 still has user 1's text in it. Give the widget a key that says which thing it is (Counter is the widget from §08):

user_counter.dart
class UserCounter extends StatelessWidget {
  const UserCounter({super.key, required this.userId});

  final int userId;

  @override
  Widget build(BuildContext context) {
    // A different key means "this is a different thing". When userId changes,
    // Flutter drops the old Counter State and creates a fresh one.
    return Counter(key: ValueKey(userId));
  }
}

Same userId, same key: the State stays. A new userId makes a different key, the rule answers "no", and you get a fresh State. React developers use key for the same trick.

When state vanishes and you wanted to keep it

highlighter.dart (inside a State)
// ✗ In one branch this spot holds a ColoredBox (with the Counter inside),
//   in the other the Counter itself. A different widget type at this spot:
//   the old element is dropped, and the Counter's State with it.
return _highlight
    ? const ColoredBox(color: Colors.yellow, child: Counter())
    : const Counter();

Before the tap, the widget at this spot is a Counter. After it, the widget at this spot is a ColoredBox. Different class, so the old element is destroyed along with the Counter's State, and a brand-new Counter starts at 0 inside the box. The fix is to keep the tree's shape the same and change only arguments:

highlighter.dart (inside a State)
// ✓ Same widget types in the same places on every build.
//   Only the colour changes, so the Counter's State stays.
return ColoredBox(
  color: _highlight ? Colors.yellow : Colors.transparent,
  child: const Counter(),
);

What const buys

Before Flutter applies the matching rule it checks something cheaper: is the new widget the very same object as the old one? If so, nothing below it can have changed, and Flutter does not visit that part of the tree at all.

leaf.dart
class Leaf extends StatelessWidget {
  const Leaf({super.key, required this.label});

  final String label;

  @override
  Widget build(BuildContext context) {
    leafBuilds.add(label); // test-only bookkeeping; never do this in an app
    return Text(label);
  }
}
dashboard.dart
class Dashboard extends StatefulWidget {
  const Dashboard({super.key, required this.user, required this.footer});

  final String user;
  final Widget footer;

  @override
  State<Dashboard> createState() => _DashboardState();
}

class _DashboardState extends State<Dashboard> {
  int _refreshes = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Refreshed $_refreshes times'),
        const Leaf(label: 'const'), // same object every build → skipped
        Leaf(label: widget.user), // new object every build → rebuilt
        widget.footer, // built by the parent, same object → skipped
        TextButton(
          onPressed: () => setState(() => _refreshes++),
          child: const Text('Refresh'),
        ),
      ],
    );
  }
}

leafBuilds is a list declared at the top of that file so that a test can see which build methods ran. It is bookkeeping for this experiment: §06's rule stands, and app code must not change anything inside build.

A test in this page's project taps Refresh and records which Leaf.build methods run. The result: only Leaf(label: widget.user).

  • const Leaf(label: 'const') is one object for the life of the app. Same object as last time: skipped.
  • widget.footer was created by the parent, which did not rebuild. Same object as last time: skipped.
  • Leaf(label: widget.user) is created anew each time build runs. It is a different object with the same contents, and Flutter does not compare contents, so it is rebuilt.

This is different from React, where memo compares props. In Flutter a child is skipped only when the widget object is identical, so const, and passing ready-made widgets in as parameters (like footer), are the two everyday ways to keep rebuilds small. §18 comes back to this when the tree is large.

Keys: when position is the wrong identity

Without keys, "which child is which" is answered by position: first child, second child, and so on. That is right for a fixed layout and wrong for a list whose items move.

counter_tile.dart
class CounterTile extends StatefulWidget {
  const CounterTile({super.key, required this.name});

  final String name; // comes from the widget

  @override
  State<CounterTile> createState() => _CounterTileState();
}

class _CounterTileState extends State<CounterTile> {
  int _taps = 0; // lives in the State

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(widget.name),
      trailing: Text('$_taps taps'),
      onTap: () => setState(() => _taps++),
    );
  }
}
Swap two tiles, with and without keys
Each tile counts its own taps in a State object. Tap a tile, then swap the two.
What Flutter holds, by position
widget: CounterTile(name: 'Ada')
held by
element #1 · State(_taps: 0)
widget: CounterTile(name: 'Grace')
held by
element #2 · State(_taps: 0)
Tap Ada a few times, then press Swap. Predict first: will the taps follow Ada?

The two versions differ by one argument:

✕ Matched by position
for (final name in _names)
  CounterTile(name: name), // ✗ matched by position
✓ Matched by key
for (final name in _names)
  CounterTile(key: ValueKey(name), name: name) // ✓ matched by key

You need keys when all three of these are true: the children are the same type, they hold state (their own State, a text field's content, a running animation), and their order or number can change. A list of plain Text rows does not need them: there is no state to mix up.

KeyIdentity comes fromUse it for
ValueKey(todo.id)a value: an id, a namelist items. The usual choice.
ObjectKey(todo)the object itselfitems without an id, when each item is a distinct object
UniqueKey()nothing: unique every time it is createdforcing a reset. Create it once and store it; a new one in every build resets the State on every rebuild.
GlobalKeythe key object, across the whole appreaching a State from outside (formKey.currentState, §12), or moving a widget between parents with its State
Practitioner§10

BuildContext is the element

In one sentenceA BuildContext is your widget's position in the tree. Almost everything you do with it is one operation: start here, walk up, and find the nearest thing of a given kind.

Every build method receives a context, and until now this page told you to pass it along. Here is what it is: the element from §09, seen through a smaller interface. It knows where this widget sits and who its ancestors are. That is why it is the thing you hand to anything that needs to look around.

X.of(context): look up the tree

page_banner.dart
class PageBanner extends StatelessWidget {
  const PageBanner({super.key, required this.text});

  final String text;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context); // nearest Theme above this widget
    final width = MediaQuery.sizeOf(context).width; // screen size, logical px

    return Container(
      width: width,
      padding: const EdgeInsets.all(16),
      color: theme.colorScheme.primaryContainer,
      child: Text(text, style: theme.textTheme.titleLarge),
    );
  }
}
  • Theme.of(context) walks up from this widget to the nearest Theme (your MaterialApp puts one at the top) and returns its data.
  • MediaQuery.sizeOf(context) does the same for information about the screen. There are siblings for other facts: MediaQuery.paddingOf(context) for notches, MediaQuery.viewInsetsOf(context) for the keyboard (§12).
  • Navigator.of(context), ScaffoldMessenger.of(context), DefaultTextStyle.of(context) follow the same pattern. of is a naming convention, not a language feature.

Calling of inside build does a second thing as well: it subscribes this widget. If the theme changes, every widget that called Theme.of(context) is rebuilt, even when nothing else about it changed. You saw this in §08 as the didChangeDependencies step.

The wrong context

A lookup starts at the context you pass and goes up. So the context has to belong to a widget that sits below the thing you are looking for. The classic way to get this wrong:

home_bad.dart
class HomeBad extends StatelessWidget {
  const HomeBad({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: const Drawer(child: Text('Menu items')),
      body: Center(
        child: FilledButton(
          // ✗ `context` is HomeBad's own spot in the tree, which is ABOVE
          //   the Scaffold it builds. Looking up from there finds nothing.
          onPressed: () => Scaffold.of(context).openDrawer(),
          child: const Text('Open menu'),
        ),
      ),
    );
  }
}

Tap the button and Flutter throws:

Scaffold.of() called with a context that does not contain a Scaffold.

The context in that build method is HomeBad's own position. The Scaffold is something HomeBad returns, so it is one level further down. Looking up from HomeBad can never find it.

Scaffold.of(context): which context?
A lookup starts at the element the context belongs to and walks up, never down.
MaterialApp↑ step 1: not a Scaffold
HomeBad← start: the context passed to HomeBad.build
Scaffold
Center
Builder
FilledButton
Starting at HomeBad, the walk goes up to MaterialApp and runs out of tree. The Scaffold is below the starting point, so it is never seen, and Flutter throws: Scaffold.of() called with a context that does not contain a Scaffold.

The fix is to use a context that starts below the Scaffold. Either move the button into its own widget class (its build gets its own context), or use Builder, a widget that exists only to hand you a context at its spot:

home_good.dart
class HomeGood extends StatelessWidget {
  const HomeGood({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: const Drawer(child: Text('Menu items')),
      body: Center(
        // ✓ Builder is a widget whose only job is to give you the context
        //   at ITS spot in the tree, which is below the Scaffold.
        child: Builder(
          builder: (context) => FilledButton(
            onPressed: () => Scaffold.of(context).openDrawer(),
            child: const Text('Open menu'),
          ),
        ),
      ),
    );
  }
}

Notice that the inner function's parameter is also named context. Inside the builder it hides the outer one, which is exactly what you want here.

red_title.dart
class RedTitle extends StatelessWidget {
  const RedTitle({super.key});

  @override
  Widget build(BuildContext context) {
    final red = ThemeData(
      colorScheme: ColorScheme.fromSeed(seedColor: Colors.red),
    );
    return Theme(
      data: red,
      // ✗ No error, just the wrong colour: `context` is above the Theme,
      //   so this reads the app's theme, not the red one.
      child: Text(
        'Sale',
        style: TextStyle(color: Theme.of(context).colorScheme.primary),
      ),
    );
  }
}

The text comes out in the app's colour, not red. The rule to remember: a widget's context cannot see anything that the same build method creates.

A snack bar is the short message that slides up from the bottom of the screen and disappears by itself, what the web calls a toast. For snack bars you don't need a Scaffold context at all. ScaffoldMessenger lives above every screen (your MaterialApp provides it), so any context inside the app finds it:

copy_button.dart
class CopyButton extends StatelessWidget {
  const CopyButton({super.key});

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.copy),
      onPressed: () {
        ScaffoldMessenger.of(context)
            .showSnackBar(const SnackBar(content: Text('Copied')));
      },
    );
  }
}

Context after an await

A context is an element, and elements are removed when their widget leaves the tree. If you await something and the user closes the screen meanwhile, you are holding the context of a screen that no longer exists.

delete_button.dart
class DeleteButton extends StatelessWidget {
  const DeleteButton({super.key, required this.delete});

  final Future<void> Function() delete;

  @override
  Widget build(BuildContext context) {
    return FilledButton(
      onPressed: () async {
        await delete(); // the user can leave this screen while we wait
        if (!context.mounted) return; // ← the element is gone: stop here
        Navigator.of(context).pop();
      },
      child: const Text('Delete'),
    );
  }
}

Navigator.of(context).pop() closes the current screen and shows the one underneath (§13). Future<void> Function() delete is a function type (§06): a function that takes nothing and returns a Future.

context.mounted is the same check as the State's mounted from §08, available on any context. Leave the if line out and the linter stops you, with a rule that is on by default:

Don't use 'BuildContext's across async gaps. Try rewriting the code to not use the 'BuildContext', or guard the use with a 'mounted' check

A test here opens a screen with this button, taps it, goes back while the delete is still running, and then lets the delete finish. context.mounted is false at that point, the handler returns, and nothing throws.

How of(context) works underneath: InheritedWidget

The mechanism behind all of those is the InheritedWidget. It is what React context is in React: a value placed high in the tree that anything below can read without it being passed down through every constructor.

class AppConfig extends InheritedWidget {
  const AppConfig({super.key, required this.apiBase, required super.child});

  final String apiBase;

  // The conventional static helper: AppConfig.of(context).
  static AppConfig of(BuildContext context) {
    // Walks up from `context` to the nearest AppConfig AND registers this
    // context as a dependent, so it rebuilds when the AppConfig changes.
    final config = context.dependOnInheritedWidgetOfExactType<AppConfig>();
    assert(config != null, 'No AppConfig found above this widget');
    return config!;
  }

  // Called when a new AppConfig replaces this one: should dependents rebuild?
  @override
  bool updateShouldNotify(AppConfig oldWidget) => apiBase != oldWidget.apiBase;
}

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

  @override
  Widget build(BuildContext context) {
    return Text('API: ${AppConfig.of(context).apiBase}');
  }
}

A test in this page's project confirms the two halves of that. With a new apiBase, the ApiLabel below it rebuilds while a const sibling that never asked for the config does not. With the same apiBase, nothing rebuilds.

You will rarely write an InheritedWidget by hand. You need to recognise the mechanism, because the state management packages in §15 are built on it.

Practitioner§11

Lists and scrolling

In one sentenceA scrolling list builds only the rows that are on screen or about to be. With ListView.builder you don't even create the others. Ten thousand rows then cost about the same as twenty.

On the web you add a library for list virtualization when a list gets long. In Flutter it is how lists work from the start.

ListView, two ways

eager_list.dart (inside a build method)
// Fine for a short, fixed list: every row widget is created right here.
return ListView(
  children: [for (var i = 0; i < 10000; i++) CountedRow(index: i)],
);
lazy_list.dart (inside a build method)
// For long or endless lists: Flutter calls itemBuilder only for the rows
// that are on screen, plus a little extra just outside it.
return ListView.builder(
  itemCount: 10000,
  itemBuilder: (context, index) => CountedRow(index: index),
);

CountedRow is a small widget for this experiment: it shows Row 12 in a ListTile, and counts how often it is created and how often its build runs. Both lists scroll, and both look the same. A test in this page's project counts what happens for 10 000 rows on a 640-high screen, each row 56 high:

Row widgets createdRow build methods run
ListView(children: […])10 00016
ListView.builder(…)1616

So even the first version only builds the rows near the screen. What it cannot avoid is creating 10 000 widget objects up front, every time the parent rebuilds, and it needs all 10 000 pieces of data in memory to do so. ListView.builder asks you for row number index only when that row is about to be needed.

Why 16 and not 12? About 11.4 rows fit on the screen. Flutter also keeps rows alive in a strip of 250 logical pixels above and below the visible area, the cache extent, so that a small scroll has nothing to wait for.

10 000 rows, how many exist?
A ListView.builder on a 640-high screen with 56-high rows. Scroll with the slider.
jump to
Row 0
Row 1
Row 2
Row 3
Row 4
Row 5
Row 6
Row 7
Row 8
Row 9
Row 10
Row 11
Row 12
Row 13
Row 14
Row 15
Rows that exist right now
16 of 10,000
rows 0 to 15
On screen
rows 0 to 11
The white outline is the phone screen. Dashed rows are built but not visible: they sit in the 250-pixel cache strip above and below, ready for the next scroll.
Everything else
itemBuilder has not been called for the other 9,984 rows. Rows that scroll out of the cache strip are destroyed again.

Separators, and keys for rows

inbox.dart
class Inbox extends StatelessWidget {
  const Inbox({super.key, required this.subjects});

  final List<String> subjects;

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: subjects.length,
      itemBuilder: (context, index) => ListTile(
        key: ValueKey(subjects[index]),
        leading: const Icon(Icons.mail),
        title: Text(subjects[index]),
      ),
      separatorBuilder: (context, index) => const Divider(height: 1),
    );
  }
}

ListView.separated calls separatorBuilder between rows: two rows get one divider, with none after the last. The key on each row is the lesson from §09: these rows can be reordered or deleted, so they are identified by their content, not their position.

Grids

photo_grid.dart
class PhotoGrid extends StatelessWidget {
  const PhotoGrid({super.key, required this.count});

  final int count;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: const EdgeInsets.all(8),
      // The delegate decides the columns. Here: always 3 across.
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
      ),
      itemCount: count,
      itemBuilder: (context, index) => ColoredBox(
        color: Colors.teal,
        child: Center(child: Text('$index')),
      ),
    );
  }
}

A GridView is a lazy list in two dimensions. The gridDelegate decides the columns. (A delegate is a helper object that a widget asks for decisions.)

  • SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3): always 3 columns, cells get whatever width that gives. On a 360-wide phone with this padding and spacing, each cell is 109.3 wide.
  • SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 150): as many columns as fit when each is at most 150 wide. This one adapts to tablets for free.

Cells are square unless you set childAspectRatio.

When every row has the same height, say so

fixed_height_list.dart (inside a build method)
return ListView.builder(
  itemCount: 10000,
  itemExtent: 56, // every row is exactly 56 high: no measuring needed
  itemBuilder: (context, index) => ListTile(title: Text('Row $index')),
);

Without itemExtent, the list has to lay out rows to learn how tall they are. To jump from the top to row 9000 it must work its way through what lies between. With itemExtent it can calculate where any row is. The framework's documentation says it directly: giving the extent "is more efficient than letting the children determine their own extent", especially "when the scroll position changes drastically".

If you don't know the height in pixels but all rows are alike, pass prototypeItem: someRowWidget instead. Flutter measures that one widget and uses its height for all of them.

Pull to refresh

feed.dart
class Feed extends StatefulWidget {
  const Feed({super.key, required this.load});

  final Future<List<String>> Function() load;

  @override
  State<Feed> createState() => _FeedState();
}

class _FeedState extends State<Feed> {
  List<String> _posts = [];

  Future<void> _refresh() async {
    final posts = await widget.load();
    if (!mounted) return;
    setState(() => _posts = posts);
  }

  @override
  void initState() {
    super.initState();
    _refresh();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refresh, // the spinner stays until this Future completes
      child: ListView.builder(
        // Lets the user pull even when the list is too short to scroll.
        physics: const AlwaysScrollableScrollPhysics(),
        itemCount: _posts.length,
        itemBuilder: (context, index) => ListTile(title: Text(_posts[index])),
      ),
    );
  }
}

RefreshIndicator wraps a scrollable, which is any widget that scrolls. When the user drags down past the top it shows a spinner and calls onRefresh. The spinner stays until the Future you return completes, so return the Future of your reload and the UI takes care of itself. physics is the parameter that decides how a scrollable reacts to dragging. It matters here when the list is short: a list that fits on screen cannot normally be dragged, and then there would be nothing to pull.

This Feed shows an empty list while the first load runs and ignores errors, to keep the example on one topic. §14 shows how to handle loading and failure properly.

Slivers

ListView and GridView are convenience widgets. Underneath, a scrollable area is a CustomScrollView containing slivers: pieces that know how to lay out just the part of themselves that is visible. You reach for slivers directly when one scroll area has to contain different kinds of content, such as a header that collapses, then a paragraph, then a long list:

profile_page.dart
class ProfilePage extends StatelessWidget {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: [
        const SliverAppBar(title: Text('Ada'), floating: true),
        const SliverToBoxAdapter(
          child: Padding(padding: EdgeInsets.all(16), child: Text('About me')),
        ),
        SliverList.builder(
          itemCount: 100,
          itemBuilder: (context, index) => ListTile(title: Text('Post $index')),
        ),
      ],
    );
  }
}

Everything in slivers: must be a sliver. SliverList and SliverGrid are the lazy list and grid, SliverAppBar is an app bar that can scroll away and come back, and SliverToBoxAdapter wraps one ordinary widget so it can sit among them. Putting an ordinary widget straight into slivers: is an error; so is putting a sliver into a Column.

Practitioner§12

User input and forms

In one sentenceButtons handle taps for you. For everything else there are two wrappers: InkWell when you want Material's ripple, GestureDetector when you want any gesture and no visual effect. Text goes through a TextField and, usually, a controller.

Taps and gestures

Widgets like Text and Container have no onTap. You make something tappable by wrapping it:

photo_card.dart
class PhotoCard extends StatelessWidget {
  const PhotoCard({super.key, required this.onOpen, required this.onLike});

  final VoidCallback onOpen;
  final VoidCallback onLike;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // GestureDetector: any gesture, on any widget, with no visual effect.
        GestureDetector(
          onDoubleTap: onLike,
          onLongPress: () => debugPrint('show the menu'),
          child: Container(width: 200, height: 120, color: Colors.teal),
        ),
        // InkWell: a tap with the Material ripple. Needs a Material above it
        // to draw on (Scaffold, Card and friends provide one).
        InkWell(
          onTap: onOpen,
          child: const Padding(
            padding: EdgeInsets.all(12),
            child: Text('Open photo'),
          ),
        ),
      ],
    );
  }
}
InkWellGestureDetector
FeedbackMaterial's ripple (a circle of colour that spreads from your finger) and highlightnone
Gesturestap, double tap, long pressthose, plus drags, pans, scale (pinch) and more
Use forrows, cards, anything that should feel like a buttonswipes, custom controls, invisible tap areas

If a list row should react to a tap, ListTile(onTap: …) already has the ripple built in.

tap_area.dart
class TapArea extends StatelessWidget {
  const TapArea({super.key, required this.onTap, required this.opaque});

  final VoidCallback onTap;
  final bool opaque;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // By default a GestureDetector only reacts where its child paints
      // something. An empty box paints nothing, so taps fall through it.
      behavior: opaque ? HitTestBehavior.opaque : HitTestBehavior.deferToChild,
      onTap: onTap,
      child: const SizedBox(width: 200, height: 80),
    );
  }
}

A test here taps the empty box in both modes: with the default, onTap is never called; with HitTestBehavior.opaque, it is. If "my tap handler doesn't fire", this is the first thing to check.

A text field

name_field.dart
class NameField extends StatefulWidget {
  const NameField({super.key});

  @override
  State<NameField> createState() => _NameFieldState();
}

class _NameFieldState extends State<NameField> {
  String _name = '';

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(
          decoration: const InputDecoration(
            labelText: 'Name',
            border: OutlineInputBorder(),
          ),
          textCapitalization: TextCapitalization.words,
          onChanged: (value) => setState(() => _name = value),
        ),
        Text(_name.isEmpty ? 'Who are you?' : 'Hello, $_name'),
      ],
    );
  }
}

A TextField keeps its own text. That is different from a React controlled input, where you must pass value back on every render or the typing does not show. In Flutter you only listen: onChanged tells you what the text is now.

InputDecoration holds everything around the text: label, hint, icons, border, error message. keyboardType, textCapitalization and textInputAction tune the on-screen keyboard.

When you need to read the text later (on a button press) or change it from code (clear it, pre-fill it), give the field a TextEditingController, a controller, and keep it in your State. You saw that pattern in §08: create it as a field, dispose it in dispose.

You need to…Use
React to every keystrokeonChanged
Read the value when a button is presseda controller, then controller.text
Set or clear the text from codea controller: controller.text = '…', controller.clear()
Validate several fields togethera Form (next)

Switches, checkboxes and dropdowns

Not every input is text. These three work differently from a TextField: they keep nothing themselves. You pass the current value in and change your own state in onChanged, exactly like a controlled input in React.

alert_settings.dart
class AlertSettings extends StatefulWidget {
  const AlertSettings({super.key});

  @override
  State<AlertSettings> createState() => _AlertSettingsState();
}

class _AlertSettingsState extends State<AlertSettings> {
  bool _email = true;
  bool _accepted = false;
  String _frequency = 'daily';

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SwitchListTile(
          title: const Text('Email me'),
          value: _email, // what it shows comes from your state …
          onChanged: (value) => setState(() => _email = value), // … every time
        ),
        CheckboxListTile(
          title: const Text('I accept the terms'),
          value: _accepted,
          onChanged: (value) => setState(() => _accepted = value ?? false),
        ),
        DropdownButton<String>(
          value: _frequency,
          items: const [
            DropdownMenuItem(value: 'daily', child: Text('Every day')),
            DropdownMenuItem(value: 'weekly', child: Text('Once a week')),
          ],
          onChanged: (value) => setState(() => _frequency = value ?? 'daily'),
        ),
        Text('email: $_email, accepted: $_accepted, $_frequency'),
      ],
    );
  }
}
WidgetForNotes
Switch, SwitchListTileon / offthe …ListTile version adds a label and makes the whole row tappable
Checkbox, CheckboxListTileagree / selectonChanged gives a bool?, because a checkbox can have a third, "mixed" state
DropdownButton<T>one of a few optionsT is the type of the values; items is a list of DropdownMenuItem
Slidera number in a range§15 uses one
showDatePicker, showTimePickerdates and timesfunctions that open a dialog and return a Future (§13)

Leave out the setState and the control does not move when tapped: it only ever shows the value you give it. A test here taps all three and reads the new values back from the text line.

Forms and validation

login_form.dart
class LoginForm extends StatefulWidget {
  const LoginForm({super.key, required this.onSubmit});

  final void Function(String email, String password) onSubmit;

  @override
  State<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  final _formKey = GlobalKey<FormState>(); // a handle on the Form's State
  final _email = TextEditingController();
  final _password = TextEditingController();

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

  void _submit() {
    // Runs every validator below and shows the error texts.
    if (!_formKey.currentState!.validate()) return;
    widget.onSubmit(_email.text.trim(), _password.text);
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            controller: _email,
            decoration: const InputDecoration(labelText: 'Email'),
            keyboardType: TextInputType.emailAddress, // shows the @ keyboard
            textInputAction: TextInputAction.next, // "next" key moves focus
            // Return an error text, or null when the value is fine.
            validator: (value) => value == null || !value.contains('@')
                ? 'Enter a valid email'
                : null,
          ),
          TextFormField(
            controller: _password,
            decoration: const InputDecoration(labelText: 'Password'),
            obscureText: true, // dots instead of characters
            textInputAction: TextInputAction.done,
            onFieldSubmitted: (_) => _submit(), // "done" key submits
            validator: (value) =>
                (value ?? '').length < 8 ? 'Use at least 8 characters' : null,
          ),
          const SizedBox(height: 16),
          FilledButton(onPressed: _submit, child: const Text('Sign in')),
        ],
      ),
    );
  }
}

A test here taps Sign in on the empty form and finds both error texts and no call to onSubmit. After typing a valid email and password, the errors are gone and onSubmit receives the trimmed email.

Validation runs when you call validate(). To also validate as the user types, set autovalidateMode: AutovalidateMode.onUserInteraction on the Form.

Focus and the keyboard

Focus decides which widget receives typing. A text field that gains focus opens the keyboard; when it loses focus the keyboard closes. Usually you let the user tap, and set autofocus: true on the field that should be ready when a screen opens. To drive it from code, use a FocusNode:

search_bar.dart
class SearchBar2 extends StatefulWidget {
  const SearchBar2({super.key});

  @override
  State<SearchBar2> createState() => _SearchBar2State();
}

class _SearchBar2State extends State<SearchBar2> {
  final _focusNode = FocusNode();

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

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(child: TextField(focusNode: _focusNode)),
        IconButton(
          icon: const Icon(Icons.search),
          onPressed: _focusNode.requestFocus, // focus the field: keyboard opens
        ),
        IconButton(
          icon: const Icon(Icons.keyboard_hide),
          // Take focus away from whatever has it: the keyboard closes.
          onPressed: () => FocusManager.instance.primaryFocus?.unfocus(),
        ),
      ],
    );
  }
}

A FocusNode is one more object that you create and must dispose. The last button shows the idiom for "close the keyboard": remove focus from whatever currently has it.

Moving from field to field needs no code: textInputAction: TextInputAction.next puts a "next" key on the keyboard, and pressing it moves focus to the next field.

When the keyboard covers the screen

The keyboard takes roughly the bottom 300 logical pixels of a phone. By default a Scaffold reacts by making its body shorter by that amount (the parameter is resizeToAvoidBottomInset, and it is true unless you change it). Whether that works out depends on what the body is.

login_screen.dart
class LoginScreen extends StatelessWidget {
  const LoginScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Sign in')),
      // Scaffold shrinks its body when the keyboard opens. A scroll view
      // lets the user reach whatever no longer fits.
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            const FlutterLogo(size: 200),
            const SizedBox(height: 32),
            LoginForm(onSubmit: (email, password) {}),
          ],
        ),
      ),
    );
  }
}

Measured in a test on a 360 × 640 screen: the content is 440 high and the body 584. With a 300-pixel keyboard the body becomes 284, the SingleChildScrollView shrinks to fit, and the user can scroll the remaining 156 pixels. Flutter also scrolls the focused field into view.

Take the scroll view away and put the same Column straight into the body, and the same keyboard produces:

A RenderFlex overflowed by 156 pixels on the bottom.

It is the overflow error from §07. The column needs 440 and now has only 284.

If you need the keyboard's height yourself, for example to lift a button above it, read MediaQuery.viewInsetsOf(context).bottom.

Practitioner§14

Loading and sending data

In one sentenceA request is in one of three states: waiting, failed, or done with data. Start it once, keep the Future, and let build draw whichever state it is in.

Your whole app runs on one thread, as JavaScript does in a browser tab, and await works the same way: it pauses that one function and lets the app keep drawing and reacting. So everything you know about fetch and await carries over. (The details of Dart's event loop are at the end of this section.)

Fetching and decoding JSON

flutter pub add http     # this page uses http 1.6

The file below imports dart:convert for jsonDecode, the http package under a prefix, and todo.dart, the file with the Todo class from §04.

lib/todo_api.dart
import 'dart:convert';

import 'package:http/http.dart' as http;

import 'todo.dart';

class TodoApi {
  TodoApi(this._client);

  final http.Client _client; // passed in, so a test can pass a fake

  Future<List<Todo>> fetchTodos() async {
    final uri = Uri.parse('https://jsonplaceholder.typicode.com/todos');
    final response = await _client.get(uri);
    if (response.statusCode != 200) {
      throw Exception('Server answered ${response.statusCode}');
    }
    // jsonDecode returns dynamic: say what you expect, then convert each item.
    final items = jsonDecode(response.body) as List<dynamic>;
    return [
      for (final item in items) Todo.fromJson(item as Map<String, dynamic>),
    ];
  }
}

Convert JSON to your own classes at the edge of the app, as this does, and the rest of your code works with Todo objects whose fields the compiler knows. Passing Map<String, dynamic> around your widgets gives up everything §03 was about.

Taking the http.Client as a constructor argument, instead of calling http.get directly, is what lets a test hand in a fake client that answers without a network (§16). In the app you create the pieces once, at the top, and pass them down: TodosScreen(api: TodoApi(http.Client())). §17 shows that wiring in a complete app.

Showing it: FutureBuilder

FutureBuilder is a widget that takes a Future and a builder function. It calls the function with a snapshot of the Future's current state, and calls it again when that state changes.

lib/todos_screen.dart
import 'package:material_ui/material_ui.dart';

import 'todo.dart';
import 'todo_api.dart';

class TodosScreen extends StatefulWidget {
  const TodosScreen({super.key, required this.api});

  final TodoApi api;

  @override
  State<TodosScreen> createState() => _TodosScreenState();
}

class _TodosScreenState extends State<TodosScreen> {
  late Future<List<Todo>> _todos;

  @override
  void initState() {
    super.initState();
    _todos = widget.api
        .fetchTodos(); // ← start the request ONCE, keep the Future
  }

  void _retry() {
    setState(() {
      _todos = widget.api
          .fetchTodos(); // a new Future: FutureBuilder starts over
    });
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Todo>>(
      future: _todos,
      builder: (context, snapshot) {
        // 1. Still waiting.
        if (snapshot.connectionState != ConnectionState.done) {
          return const Center(child: CircularProgressIndicator());
        }
        // 2. Finished with an error.
        if (snapshot.hasError) {
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('Could not load: ${snapshot.error}'),
                TextButton(onPressed: _retry, child: const Text('Try again')),
              ],
            ),
          );
        }
        // 3. Finished with data.
        final todos = snapshot.data!;
        return ListView.builder(
          itemCount: todos.length,
          itemBuilder: (context, index) =>
              ListTile(title: Text(todos[index].label)),
        );
      },
    );
  }
}

Play the server and watch what the builder receives:

FutureBuilder: three states, one snapshot
You play the server. The phone shows what the builder from the code above returns.
requests sent: 1
The snapshot your builder receives
connectionState: ConnectionState.waiting
hasData: false
hasError: false
The Future is running and nothing has arrived: the builder's first if returns the spinner.

The snapshot has three things worth reading, and the order you check them in matters:

  1. snapshot.connectionState: waiting while the Future runs, done when it has finished either way.
  2. snapshot.hasError and snapshot.error.
  3. snapshot.hasData and snapshot.data.

When you give a FutureBuilder a new Future (the retry), the snapshot keeps the previous data or error until the new one finishes. That is deliberate, so you could keep showing old data with a small spinner on top. It is also why this builder asks about connectionState first.

The mistake everyone makes once

todos_screen_bad.dart (inside a build method)
return FutureBuilder<List<Todo>>(
  future: api.fetchTodos(), // ✗ a new request on every single rebuild
  builder: (context, snapshot) {
    if (snapshot.connectionState != ConnectionState.done) {
      return const Center(child: CircularProgressIndicator());
    }
    return Text('${snapshot.data!.length} todos');
  },
);

build runs often, and you don't control when: the keyboard opens, the theme changes, a parent calls setState. Each time, api.fetchTodos() starts a new request and hands FutureBuilder a new Future, so it goes back to waiting. A test here rebuilds the parent once: the fake server receives a second request and the spinner is back on screen.

The framework's documentation for FutureBuilder states the rule: the Future must have been obtained earlier, for example in initState, didUpdateWidget or didChangeDependencies, and must not be created during build. That is what late Future<List<Todo>> _todos in the first version is for.

Sending data

Reading is half of it. To create something on the server you send a POST request with a JSON body:

lib/create_todo.dart
import 'dart:convert';

import 'package:http/http.dart' as http;

import 'todo.dart';

Future<Todo> createTodo(http.Client client, String title) async {
  final response = await client.post(
    Uri.parse('https://jsonplaceholder.typicode.com/todos'),
    // Tell the server that the body is JSON.
    headers: {'Content-Type': 'application/json'},
    // jsonEncode is JSON.stringify: a Map goes in, a String comes out.
    body: jsonEncode({'title': title, 'completed': false}),
  );
  if (response.statusCode != 201) {
    throw Exception('Server answered ${response.statusCode}');
  }
  // The server answers with the created todo, including its new id.
  return Todo.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
  • jsonEncode is JSON.stringify. You give it a Map (or a List) of plain values and get a String.
  • The Content-Type header tells the server the body is JSON. Without it many servers reject or misread the request.
  • 201 is the status for "created". Which status means success depends on the API; check it and throw otherwise.
  • In a real app this would be a second method on TodoApi. §17 does that.

A save button has more to do than send the request. While the request runs it must not be pressed again, the user should see that something is happening, and a failure must reach the user without losing what they typed:

lib/add_todo.dart
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';

import 'create_todo.dart';
import 'todo.dart';

class AddTodo extends StatefulWidget {
  const AddTodo({super.key, required this.client, required this.onAdded});

  final http.Client client;
  final ValueChanged<Todo> onAdded;

  @override
  State<AddTodo> createState() => _AddTodoState();
}

class _AddTodoState extends State<AddTodo> {
  final _title = TextEditingController();
  bool _saving = false;

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

  Future<void> _save() async {
    setState(() => _saving = true); // 1. show that work is going on
    try {
      final todo = await createTodo(widget.client, _title.text);
      if (!mounted) return;
      _title.clear();
      widget.onAdded(todo); // 2a. success: hand the result to the parent
    } catch (error) {
      if (!mounted) return;
      // 2b. failure: tell the user, keep what they typed
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Could not save: $error')));
    } finally {
      if (mounted) setState(() => _saving = false); // 3. either way: done
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: TextField(controller: _title, enabled: !_saving),
        ),
        if (_saving)
          const CircularProgressIndicator()
        else
          IconButton(icon: const Icon(Icons.send), onPressed: _save),
      ],
    );
  }
}

The tests for this widget use a fake client. With a slow answer they see the spinner and no send button, then the parent receives the new todo and the field is empty. With a 500 they see the snack bar Could not save: Exception: Server answered 500, the typed text still there, and the button back.

StreamBuilder

A Stream delivers many values (§05). StreamBuilder is the same idea as FutureBuilder, with the builder called once per value:

countdown.dart
class Countdown extends StatefulWidget {
  const Countdown({super.key, required this.from});

  final int from;

  @override
  State<Countdown> createState() => _CountdownState();
}

class _CountdownState extends State<Countdown> {
  late final Stream<int> _ticks;

  @override
  void initState() {
    super.initState();
    // One value per second: from − 1, from − 2, … 0. Created once, like a Future.
    _ticks = Stream.periodic(
      const Duration(seconds: 1),
      (count) => widget.from - 1 - count,
    ).take(widget.from);
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<int>(
      stream: _ticks,
      initialData: widget.from, // shown until the first value arrives
      builder: (context, snapshot) {
        // The builder runs again for every value the stream emits.
        final left = snapshot.data!;
        return Text(left == 0 ? 'Lift off' : '$left');
      },
    );
  }
}

The same rule applies: create the stream once, outside build. StreamBuilder subscribes when it appears and cancels the subscription when it is removed, so there is no cleanup for you to write. You will use it for live data: a chat, a location feed, a database query that updates.

Or do it by hand

FutureBuilder is a convenience. The same screen with plain state looks like this (the file imports material_ui and todo_api.dart):

todo_count.dart
class TodoCount extends StatefulWidget {
  const TodoCount({super.key, required this.api});

  final TodoApi api;

  @override
  State<TodoCount> createState() => _TodoCountState();
}

class _TodoCountState extends State<TodoCount> {
  int? _count; // null while loading
  Object? _error;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    try {
      final todos = await widget.api.fetchTodos();
      if (!mounted) return; // the screen was closed while we waited
      setState(() => _count = todos.length);
    } catch (error) {
      if (!mounted) return;
      setState(() => _error = error);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_error != null) return Text('Failed: $_error');
    if (_count == null) return const CircularProgressIndicator();
    return Text('$_count todos');
  }
}

Object? _error can hold any value or null (§04): whatever was thrown, if anything. It is more lines than FutureBuilder, and in exchange you decide exactly what each state is (you could keep the old count visible while reloading, for instance). _load is an async method called from initState without await, the pattern from §08. Note the mounted check after the await, on both paths. A test here closes the widget while the request is still running and lets it finish afterwards; nothing throws.

Why await does not freeze the app

Dart has an event loop with the same two queues you may know from The Event Loop → Queues: a microtask queue, emptied after each piece of running code, and an event queue for timers, taps, network answers and everything else. The code after an await is put on a queue and runs later, and in between the loop is free to draw frames and handle taps.

void order(void Function(String) log) {
  log('1 sync');
  Future(
    () => log('4 event'),
  ); // goes to the event queue, like setTimeout(f, 0)
  scheduleMicrotask(() => log('3 microtask')); // like queueMicrotask(f)
  log('2 sync');
}

The numbers in the strings are the order a test observed. (scheduleMicrotask comes from dart:async.) What does freeze the app is long synchronous work with no await in it, and Dart has a different answer for that (isolates, §18).

Practitioner§15

Sharing state between screens

In one sentenceKeep state in the lowest widget that covers everyone who needs it. When that widget is the whole app, move the state out of the widget tree into an object that widgets can listen to.

setState inside one widget is the right tool for state only that widget cares about: is this box ticked, which tab is selected, what has been typed so far. This section is about state that two or more places need. The reasoning is the same as on the web, and State Management covers it in depth.

Step 1: lift it up

Two siblings need the same value. Move it to their closest common parent, pass the value down through constructors and pass changes up through callbacks.

tip_calculator.dart
class TipCalculator extends StatefulWidget {
  const TipCalculator({super.key});

  @override
  State<TipCalculator> createState() => _TipCalculatorState();
}

class _TipCalculatorState extends State<TipCalculator> {
  int _percent = 10; // owned by the closest common parent of both children

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // Data goes down through the constructor …
        TipLabel(percent: _percent),
        // … and changes come back up through a callback.
        TipSlider(
          percent: _percent,
          onChanged: (value) => setState(() => _percent = value),
        ),
      ],
    );
  }
}

class TipLabel extends StatelessWidget {
  const TipLabel({super.key, required this.percent});

  final int percent;

  @override
  Widget build(BuildContext context) => Text('Tip: $percent%');
}

class TipSlider extends StatelessWidget {
  const TipSlider({super.key, required this.percent, required this.onChanged});

  final int percent;
  final ValueChanged<int> onChanged;

  @override
  Widget build(BuildContext context) {
    return Slider(
      value: percent.toDouble(),
      max: 30,
      divisions: 30,
      onChanged: (value) => onChanged(value.round()),
    );
  }
}

ValueChanged<int> is a ready-made name for the function type void Function(int) (§06). The slider doesn't own the percentage; it reports what the user did, and the parent decides. This is "lifting state up", exactly as in React (State Management → Local and lifted), and you should stay with it for as long as it stays comfortable.

It stops being comfortable when the value has to travel through five widgets that don't care about it, or when setState at the top rebuilds a whole screen for one changed number.

Step 2: an object you can listen to

Flutter has a small type called Listenable: any object you can subscribe to with addListener. The one you will use most is ChangeNotifier. You extend it, keep your state in fields, and call notifyListeners() after each change:

lib/cart.dart
class Cart extends ChangeNotifier {
  final List<String> _items = [];

  List<String> get items => List.unmodifiable(_items); // read-only view
  int get count => _items.length;

  void add(String item) {
    _items.add(item);
    notifyListeners(); // ← without this call nobody hears about the change
  }

  void clear() {
    _items.clear();
    notifyListeners();
  }
}

Cart is plain Dart with no widgets in it, so it is easy to unit test. To show it, wrap the part of the UI that depends on it in a ListenableBuilder, which calls its builder again whenever the listenable notifies:

cart_badge.dart
class CartBadge extends StatelessWidget {
  const CartBadge({super.key, required this.cart});

  final Cart cart;

  @override
  Widget build(BuildContext context) {
    return ListenableBuilder(
      listenable: cart, // any ChangeNotifier, ValueNotifier or Animation
      builder: (context, child) => Text('Cart (${cart.count})'),
    );
  }
}

For a single value there is a ready-made notifier, ValueNotifier, with its own builder widget. It is handy for keeping a rebuild small inside a big screen:

like_screen.dart
class LikeScreen extends StatefulWidget {
  const LikeScreen({super.key});

  @override
  State<LikeScreen> createState() => _LikeScreenState();
}

class _LikeScreenState extends State<LikeScreen> {
  final _likes = ValueNotifier<int>(0); // one value + a list of listeners

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

  @override
  Widget build(BuildContext context) {
    likeScreenBuilds++; // test-only counter: this build runs once
    return Column(
      children: [
        const Text('A long article …'),
        // Only this builder runs again when _likes.value changes.
        ValueListenableBuilder<int>(
          valueListenable: _likes,
          builder: (context, likes, child) => Text('$likes likes'),
        ),
        IconButton(
          icon: const Icon(Icons.favorite),
          onPressed: () => _likes.value++, // setting .value notifies listeners
        ),
      ],
    );
  }
}

There is no setState in that class. A test here taps the heart twice: the text says "2 likes", and _LikeScreenState.build ran once. Only the small builder function ran again. (likeScreenBuilds is a counter for that test, declared at the top of the file. App code never changes anything in build.)

Step 3, and where to start: provider

CartBadge still gets the cart through its constructor. Two questions are left: who creates the Cart, and how does a widget ten levels down find it without it being passed through every constructor in between?

The provider package answers both with one widget. It is the smallest step up from what you just read, which is why this page recommends it for a first app.

flutter pub add provider     # this page uses provider 6.1

The file needs import 'package:provider/provider.dart';, next to material_ui and your own cart.dart.

lib/shop_app.dart (provider 6.1)
class ShopApp extends StatelessWidget {
  const ShopApp({super.key});

  @override
  Widget build(BuildContext context) {
    // Creates the Cart once, offers it to everything below, disposes it
    // when ShopApp goes away.
    return ChangeNotifierProvider(
      create: (context) => Cart(),
      child: const MaterialApp(home: ShopScreen()),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    // watch: read the Cart AND rebuild this widget when it notifies.
    final cart = context.watch<Cart>();
    return Scaffold(
      appBar: AppBar(title: Text('Cart (${cart.count})')),
      body: Center(
        child: FilledButton(
          // read: get the Cart once, without subscribing. Use it in callbacks.
          onPressed: () => context.read<Cart>().add('Tea'),
          child: const Text('Add tea'),
        ),
      ),
    );
  }
}
  • ChangeNotifierProvider(create: …) creates the Cart once, offers it to every widget below, and disposes it when it is removed. Put it above MaterialApp so that every screen can reach it.
  • context.watch<Cart>() in build: find the nearest Cart above and rebuild this widget whenever it notifies. The <Cart> is a type argument on the call (§04).
  • context.read<Cart>() in a callback: find it once, without subscribing.
  • Mixing those up is the usual mistake. watch in a callback throws an error in debug mode; read in build compiles, and the widget then never updates.

watch and read look up the tree from your context, like Theme.of(context) in §10. So the limits are the ones you know from there: you need a BuildContext, and the provider must sit above everyone who uses it. For an app with a handful of shared objects that is rarely a problem. §17 builds a complete app this way.

How provider works underneath

Without the package, the two questions have these answers. Who creates the Cart: a State near the top of the app creates it once and disposes it. How do widgets far below find it: through the InheritedWidget mechanism from §10, and Flutter has a class that combines it with a notifier:

cart_scope.dart
class CartScope extends InheritedNotifier<Cart> {
  const CartScope({super.key, required Cart cart, required super.child})
    : super(notifier: cart);

  // Any widget below can call CartScope.of(context). It then rebuilds
  // whenever the cart calls notifyListeners().
  static Cart of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<CartScope>()!.notifier!;
  }
}

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

  @override
  Widget build(BuildContext context) {
    final cart = CartScope.of(context);
    return Text('${cart.count} items in your cart');
  }
}

class AddToCartButton extends StatelessWidget {
  const AddToCartButton({super.key, required this.item});

  final String item;

  @override
  Widget build(BuildContext context) {
    return FilledButton(
      onPressed: () => CartScope.of(context).add(item),
      child: Text('Add $item'),
    );
  }
}
shop.dart
class Shop extends StatefulWidget {
  const Shop({super.key, required this.child});

  final Widget child;

  @override
  State<Shop> createState() => _ShopState();
}

class _ShopState extends State<Shop> {
  final _cart = Cart(); // created once; lives as long as this State does

  @override
  void dispose() {
    _cart.dispose(); // a ChangeNotifier is disposed like a controller
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CartScope(cart: _cart, child: widget.child);
  }
}

Wrap your app in Shop(child: …), and you have written ChangeNotifierProvider yourself: Shop is its create and dispose, CartScope.of(context) is context.watch<Cart>(). Every widget below that calls CartScope.of(context) in its build is now rebuilt whenever the cart notifies. A test here taps the add button and sees CartTotal, a sibling that shares no parent state with the button, change from 0 to 1 items.

Packages you will meet: Riverpod

Riverpod, by the same author, moves the state out of the widget tree. Providers are declared as global variables; the state itself lives in a ProviderScope at the root. The code below is Riverpod 3 (flutter_riverpod 3.5, added with flutter pub add flutter_riverpod and imported as package:flutter_riverpod/flutter_riverpod.dart). Version 3 changed several names, so tutorials for 2.x will not match it line for line.

counter_riverpod.dart (flutter_riverpod 3.5)
// A provider is a global, but it only holds the recipe. The state itself
// lives in the ProviderScope at the top of the app.
final counterProvider = NotifierProvider<CounterNotifier, int>(
  CounterNotifier.new,
);

class CounterNotifier extends Notifier<int> {
  @override
  int build() => 0; // the initial state

  void increment() => state++; // assigning to state notifies the watchers
}

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

  @override
  Widget build(BuildContext context) {
    return const ProviderScope(child: MaterialApp(home: CounterScreen()));
  }
}

// ConsumerWidget is a StatelessWidget whose build also receives a `ref`.
class CounterScreen extends ConsumerWidget {
  const CounterScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider); // rebuilds when it changes
    return Scaffold(
      body: Center(child: Text('Count: $count')),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ref.read(counterProvider.notifier).increment(),
        child: const Icon(Icons.add),
      ),
    );
  }
}

Its strongest feature is async data. A FutureProvider runs a Future once, caches the result, and hands widgets an AsyncValue for the three states from §14:

todos_count.dart (flutter_riverpod 3.5)
final todosProvider = FutureProvider<List<Todo>>((ref) => loadTodos());

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // An AsyncValue is loading, data or error: the three states from §14,
    // as one sealed type that `switch` can take apart.
    final todos = ref.watch(todosProvider);
    return switch (todos) {
      AsyncData(:final value) => Text('${value.length} todos'),
      AsyncError(:final error) => Text('Failed: $error'),
      _ => const CircularProgressIndicator(),
    };
  }
}

loadTodos() stands for your own top-level function that returns the list, such as a call to TodoApi.fetchTodos from §14. The switch is the pattern matching from §05: AsyncData(:final value) matches the "has data" state and pulls the value out, and _ is the "everything else" line. Two screens that watch todosProvider share one request and one cached result.

todos_retry.dart (flutter_riverpod 3.5)
// Never retry: the first failure is shown straight away.
final todosOnceProvider = FutureProvider<List<Todo>>(
  (ref) => loadTodos(),
  retry: (retryCount, error) => null, // null means "give up"
);

// Retry twice, one second apart, then show the error.
final todosTwiceProvider = FutureProvider<List<Todo>>(
  (ref) => loadTodos(),
  retry: (retryCount, error) =>
      retryCount < 2 ? const Duration(seconds: 1) : null,
);

Packages you will meet: Bloc

Bloc (flutter pub add flutter_bloc, imported as package:flutter_bloc/flutter_bloc.dart) is built around a stricter idea: the UI may not change state at all. It calls a method, and the bloc emits a new state object; the UI rebuilds from the stream of states. Its simplest form is a Cubit:

counter_cubit.dart (flutter_bloc 9.1)
class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0); // the initial state

  void increment() => emit(state + 1); // emit a NEW state; listeners rebuild
}

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CounterCubit(),
      child: BlocBuilder<CounterCubit, int>(
        builder: (context, count) => TextButton(
          onPressed: () => context.read<CounterCubit>().increment(),
          child: Text('Count: $count'),
        ),
      ),
    );
  }
}

CounterCubit() : super(0) passes the initial state to the parent class (§04). A full Bloc adds event classes in front, so that every change is a named event. That is more code for a counter, and it pays off in large teams: every state is an immutable object you can log and test, and there is one obvious place for each piece of logic.

Choosing

SituationReach for
State used by one widgetsetState
A couple of nearby widgetslift it up, pass callbacks
One value that changes often inside a big screenValueNotifier + ValueListenableBuilder
Your first app, and most small appsChangeNotifier + provider
Lots of server data, caching, state that depends on other stateRiverpod
A large team that wants one enforced pattern and a record of every state changeBloc

All of these work, and apps of every size ship with each of them. A codebase that mixes three is much harder to work in than one that uses any single approach everywhere. Pick one per app, and move to another only when you can name what is hurting.

Practitioner§16

Testing: unit, widget and integration tests

In one sentenceA widget test builds your real widgets on a fake screen, taps and types like a user, and checks what is shown, in milliseconds and without a phone. Write many of them.

Every "a test here…" sentence on this page refers to a test like the ones below. flutter create already set everything up: the flutter_test package is in pubspec.yaml, and there is a test/ folder with one example.

Three kinds

Flutter has the usual test pyramid, with an unusually good middle layer.

KindRunsSpeedTests
Unit testplain Dart, no UImillisecondsmodels, parsing, business rules
Widget testreal widgets on a fake screen, no devicemilliseconds to tens of msone widget or screen: what it shows, what a tap does
Integration testthe whole app on a device or emulatorseconds to minutescritical journeys, plugins, performance
flutter test                      # unit and widget tests in test/
flutter test test/cart_test.dart  # one file
flutter analyze                   # the analyzer: type errors and lint rules, for CI

A unit test and a widget test

Test files live in test/, end in _test.dart, and have a main() that registers tests. A test file imports package:flutter_test/flutter_test.dart, material_ui if it builds widgets, and your own code by its package path (§04): package:my_app/todo.dart, where my_app is the name: in your pubspec.yaml. The two tests below need Todo (§04) and Counter (§08), so they import the files you put those in.

test/example_test.dart (inside main)
// A unit test: plain Dart, no widgets, runs in milliseconds.
test('Todo.fromJson reads the API shape', () {
  final todo = Todo.fromJson({
    'id': 7,
    'title': 'Call mum',
    'completed': true,
  });

  expect(todo.id, 7);
  expect(todo.label, '✓ Call mum');
});
test/example_test.dart (inside main)
// A widget test: builds real widgets on a fake screen, no device needed.
testWidgets('Counter adds its step on every tap', (tester) async {
  // 1. Build the widget (it needs a MaterialApp around it for text and theme).
  await tester.pumpWidget(
    const MaterialApp(home: Scaffold(body: Counter(step: 2))),
  );
  expect(find.text('Count: 0'), findsOneWidget);

  // 2. Act like a user.
  await tester.tap(find.text('Add'));
  await tester.pump(); // 3. Let Flutter draw the next frame.

  // 4. Check what is on screen now.
  expect(find.text('Count: 2'), findsOneWidget);
  expect(find.text('Count: 0'), findsNothing);
});

Faking the server

A test must not depend on a real server. This is why §14 passed the http.Client in: a test passes a fake one. The http package ships it. This test file imports dart:convert (for jsonDecode), package:http/http.dart as http, package:http/testing.dart (for MockClient), flutter_test, and package:my_app/create_todo.dart from §14.

test/post_test.dart (inside main)
// MockClient comes from package:http/testing.dart. It never touches the
// network: your function receives each request and returns the response.
test('createTodo POSTs JSON and decodes the answer', () async {
  late http.Request sent;
  final client = MockClient((request) async {
    sent = request;
    return http.Response(
      '{"id": 201, "title": "Tea", "completed": false}',
      201,
    );
  });
  final todo = await createTodo(client, 'Tea');
  expect(sent.method, 'POST');
  expect(sent.headers['Content-Type'], startsWith('application/json'));
  expect(jsonDecode(sent.body), {'title': 'Tea', 'completed': false});
  expect(todo.id, 201);
});

The same trick works one level up. A widget test for a whole screen builds the screen with an API object that wraps a MockClient, and then checks for the spinner, the list, and the error message. §17 has a complete example.

Integration tests

An integration test uses the same API, and runs inside the real app on a device or emulator. It needs one more package, which comes with the SDK and has to be added to pubspec.yaml by hand:

pubspec.yaml (part)
dev_dependencies:
  flutter_test:
    sdk: flutter
  integration_test:
    sdk: flutter
integration_test/app_test.dart
import 'package:my_app/main.dart'; // my_app is the name: in pubspec.yaml
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:material_ui/material_ui.dart';

void main() {
  // Runs the test inside the real app, on a real device or emulator.
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('the whole app: tap + and the counter goes up', (tester) async {
    await tester.pumpWidget(const MyApp());

    await tester.tap(find.byIcon(Icons.add));
    await tester.pumpAndSettle(); // wait until nothing is animating

    expect(find.text('1'), findsOneWidget);
  });
}

The first import is the app under test, by its package path.

flutter test integration_test     # needs a connected device or a running emulator

Keep integration tests for the handful of flows that must never break (sign in, pay, the main screen loads), and for anything that involves a plugin, which widget tests cannot run. The general ideas behind all three kinds are in Unit Testing and End-to-End Testing.

Practitioner§17

Putting it together: a Notes app in seven files

In one sentenceEvery piece of this app comes from an earlier section. What is new is where each piece is created and how the files reach each other: one main() builds the API object, the shared model sits above the router, and screens talk only to the model.

The app keeps a list of notes on a server. It has three screens: the list, one note, and a form for a new note. It is about 350 lines in seven files, and it is the answer to "I understood the sections; how do I start my own app?".

Set up

Create a new project named notes, add the four packages, and put the seven files in lib/ (lib/main.dart replaces the generated one):

flutter create notes && cd notes
flutter pub add material_ui go_router provider http

Then delete test/widget_test.dart. It tests the generated counter app, which you have just replaced, and it still has the old Material import from §02. If you leave it, flutter analyze reports The name 'MyApp' isn't a class.

FileWhat it holdsFrom
lib/note.dartthe Note class with fromJson§04
lib/notes_api.dartNotesApi: every HTTP call§14
lib/notes_model.dartNotesModel: the shared state, a ChangeNotifier§15
lib/main.dartmain(), the provider, the router§13, §15
lib/notes_screen.dartthe list, with loading, error and empty states§11, §14
lib/note_screen.dartone note§13
lib/new_note_screen.dartthe form that saves a note§12, §14

The files, one at a time

Step through them in the order the data flows: from the server's JSON up to the screens. Each step says which files this one imports and what to notice. The code is complete: copy the seven files and the app runs.

The Notes app, file by file
Seven files in lib/. Follow them in order, or click a file.
lib/
note.dart imports none of the other files.
Step 1 of 7 · The data
Start with the shape of the data. Note is an immutable class with a fromJson named constructor (§04). Every other file works with Note objects, never with raw JSON maps. It imports nothing.
lib/note.dart
/// One note, as the rest of the app sees it.
class Note {
  const Note({required this.id, required this.title, required this.body});

  /// Builds a Note from the JSON the server sends.
  Note.fromJson(Map<String, dynamic> json)
    : id = json['id'] as int,
      title = json['title'] as String,
      body = json['body'] as String;

  final int id;
  final String title;
  final String body;
}

One tap, followed through the files

The user fills in the form and presses Save. This is everything that happens, and where:

  1. new_note_screen.dart: _save() runs the validators, sets _saving, and calls context.read<NotesModel>().add(…).
  2. notes_model.dart: add calls _api.createNote(…) and waits.
  3. notes_api.dart: createNote sends the POST with a JSON body, checks for status 201, and turns the answer into a Note.
  4. notes_model.dart: back in add, the new note is put at the front of the list, and notifyListeners() is called.
  5. notes_screen.dart: it called context.watch<NotesModel>(), so it is rebuilt with the new list, although it is not even visible at this moment.
  6. new_note_screen.dart: the await is over. After the mounted check, context.go('/') shows the list, with the new note already on top. No second request was needed.

If step 3 throws, steps 4 and 5 never happen. The error travels back up through the two awaits into the catch in _save(), which shows a snack bar and re-enables the button.

Three decisions in this app are worth copying into yours:

  • One place creates things. main() creates the http.Client and the NotesApi. The provider creates the NotesModel. Nothing else in the app says NotesApi(…) or http.Client(), which is what makes the app testable.
  • Screens don't know about HTTP. They call methods on the model and draw its state. You could swap the server for a local database by changing one file.
  • The shared state sits above the router. Because the ChangeNotifierProvider wraps MaterialApp.router, every screen, whichever route it belongs to, finds the model above it.

Its tests

The tests replace the real http.Client with a small fake server that lives inside the test. Because NotesApp takes its NotesApi as a parameter, nothing else has to change:

test/notes_app_test.dart (part)
/// A server that lives in the test: it answers GET and POST on /posts.
class FakeServer {
  final List<Map<String, Object>> posts = [
    {'id': 1, 'title': 'Shopping', 'body': 'Milk, eggs'},
    {'id': 2, 'title': 'Ideas', 'body': 'Learn Flutter'},
  ];
  bool down = false;
  final List<http.Request> received = [];

  late final NotesApi api = NotesApi(MockClient(_handle));

  Future<http.Response> _handle(http.Request request) async {
    received.add(request);
    if (down) return http.Response('', 503);
    if (request.method == 'POST') {
      final sent = jsonDecode(request.body) as Map<String, dynamic>;
      final created = <String, Object>{
        'id': 101,
        'title': sent['title'] as String,
        'body': sent['body'] as String,
      };
      posts.insert(0, created);
      return http.Response(jsonEncode(created), 201);
    }
    return http.Response(jsonEncode(posts), 200);
  }
}
test/notes_app_test.dart (inside main)
testWidgets('new note: validate, POST, and the list shows it', (
  tester,
) async {
  final server = FakeServer();
  await tester.pumpWidget(NotesApp(api: server.api));
  await tester.pumpAndSettle();

  await tester.tap(find.byIcon(Icons.add));
  await tester.pumpAndSettle();
  await tester.tap(find.text('Save')); // empty title
  await tester.pump();
  expect(find.text('Give the note a title'), findsOneWidget);

  await tester.enterText(find.byType(TextFormField).first, 'Call mum');
  await tester.enterText(find.byType(TextFormField).last, 'On Sunday');
  await tester.tap(find.text('Save'));
  await tester.pumpAndSettle();

  // Back on the list, with the new note on top, and no second GET.
  expect(find.text('Call mum'), findsOneWidget);
  final post = server.received.last;
  expect(post.method, 'POST');
  expect(jsonDecode(post.body), {'title': 'Call mum', 'body': 'On Sunday'});
  expect(server.received.where((r) => r.method == 'GET').length, 1);
});

Save both in test/notes_app_test.dart, with the test inside void main() { … }. The file starts with seven imports: dart:convert; package:flutter_test/flutter_test.dart; package:http/http.dart with as http; package:http/testing.dart (for MockClient); package:material_ui/material_ui.dart; and the app's own two files by package path, package:notes/main.dart and package:notes/notes_api.dart (notes is the project's name). In this page's own project the app sits in a sub-folder, and six more tests in the same file cover the first load, a server that is down and then recovers, opening a note and going back without a refetch, a failed save, a link to a note while the server is down, and the path /note/abc.

Staff-level§18

How a frame is made, and how to stay fast

In one sentenceA phone screen asks for a new picture 60 or 120 times a second. For each one Flutter runs your Dart code (build, layout, paint) on one thread and turns the result into pixels on another. A frame is late when either side takes too long.

One frame, step by step

The display sends a signal, vsync, each time it is ready for a new picture. If something has changed, Flutter then produces a Frame. The five phases below are simplified from the framework's own description of drawFrame, which lists ten:

  1. Animate. Every running animation controller moves forward one tick (§08).
  2. Build. Every dirty element is rebuilt: your build methods run (§09).
  3. Layout. Render objects whose inputs changed work out their sizes: constraints down, sizes up (§07).
  4. Paint. Render objects that look different record their drawing commands ("a rounded rectangle here, this text there"). Nothing is on screen yet; this produces a list of commands, grouped into layers.
  5. Raster. The finished layers are handed to the engine, which rasterizes them: the GPU turns the commands into actual pixels.

Steps 1 to 4 are Dart, running on the UI thread. Step 5 is the engine, on the raster thread. Both must finish inside the frame budget: 16.7 ms on a 60 Hz screen, 8.3 ms on a 120 Hz one. Miss it and the display repeats the previous picture, which the user sees as stutter.

One frame, two threads
Three vsync intervals on a 60 Hz screen (16.7 ms each). Numbers are illustrative.
vsync
0 ms
16.7 ms
33.3 ms
UI thread
build·layout·paint
frame 2
frame 3
raster
raster
raster
raster
screen
previous
frame 1
frame 2
Each vsync starts a frame. Your Dart code builds, lays out and paints in about 6 ms on the UI thread, then the raster thread turns the result into pixels in about 5 ms. Both finish before the next vsync, so the display shows a new frame every 16.7 ms.

The two slow cases need different fixes, which is why the tools show you two separate graphs. Most of this section is about the UI thread, because that is where your code runs.

1. Rebuild less

A setState runs that State's whole build method again and, below it, rebuilds every child that is a new widget object (§09). So the cost of a rebuild depends on how high in the tree the setState is called.

The two versions below differ in one thing only: where the tap count lives. BigChart stands for any widget that is expensive to build. It takes its data as a parameter, so it cannot be const.

✕ State next to the chart
class ReportScreenSlow extends StatefulWidget {
  const ReportScreenSlow({super.key, required this.points});

  final List<double> points;

  @override
  State<ReportScreenSlow> createState() => _ReportScreenSlowState();
}

class _ReportScreenSlowState extends State<ReportScreenSlow> {
  int _taps = 0; // ✗ the state lives in the same State as the chart

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        BigChart(points: widget.points), // a new widget object on every build
        TextButton(
          onPressed: () => setState(() => _taps++), // rebuilds all of this
          child: Text('Tapped $_taps times'),
        ),
      ],
    );
  }
}
✓ State in its own small widget
class ReportScreen extends StatelessWidget {
  const ReportScreen({super.key, required this.points});

  final List<double> points;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        BigChart(points: points), // this build method runs once
        const TapCounter(), // ✓ the state moved into its own small widget
      ],
    );
  }
}

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

  @override
  State<TapCounter> createState() => _TapCounterState();
}

class _TapCounterState extends State<TapCounter> {
  int _taps = 0;

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: () => setState(() => _taps++), // rebuilds only this button
      child: Text('Tapped $_taps times'),
    );
  }
}

A test here taps the button twice in each version and counts how often the chart's build runs: 3 times on the left (once at the start, once per tap), once on the right. On the right, setState runs _TapCounterState.build and nothing else; ReportScreen.build, which creates the chart widget, is never called again.

So the first habit is push state down: give the part that changes its own small StatefulWidget. Then setState rebuilds a button instead of a screen. The second is the one from §06: const wherever the compiler allows it.

Helper methods are not a boundary

You will see the advice "extract widgets, not helper methods". The reason is often given wrongly, so here it is with a test.

title_bar.dart
class TitleBar extends StatefulWidget {
  const TitleBar({super.key, required this.title});

  final String title;

  @override
  State<TitleBar> createState() => _TitleBarState();
}

class _TitleBarState extends State<TitleBar> {
  int _taps = 0;

  // A helper method only moves code around. What it returns is judged by
  // the same rule as anything else in build: same object, or a new one?
  Widget _buildLogo() => const Leaf(label: 'logo'); // same object: skipped
  Widget _buildTitle() => Leaf(label: widget.title); // new object: rebuilt

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        _buildLogo(),
        _buildTitle(),
        TextButton(
          onPressed: () => setState(() => _taps++),
          child: Text('Tapped $_taps times'),
        ),
      ],
    );
  }
}

A test here taps the button and records which Leaf.build methods run (Leaf is the logging widget from §09): only the one from _buildTitle(). The const widget returned by _buildLogo() is skipped, exactly as if it had been written inline. A method call changes nothing about the rule from §09: same widget object, skipped; new object, rebuilt.

What a helper method cannot do is the things only a widget class can: it has no element of its own, so it cannot hold state, it gets no context of its own (§10), and its whole result cannot be made const from the outside. When a piece of UI needs any of those, or is used in more than one place, make it a class. For a few lines of layout used once, a method is fine.

Lists have their own rule: use the lazy constructors (§11).

2. Repaint less

Painting works in layers. When one render object needs repainting, everything in the same layer is painted again with it, because a layer is recorded as a whole. Usually that is fine. It hurts when something small animates forever next to something expensive to paint.

map_with_spinner.dart (inside a build method)
return Stack(
  children: [
    expensiveMap, // costly to paint, never changes
    // The spinner repaints 60 times a second. The boundary gives it its
    // own layer, so those repaints stop at the boundary.
    const RepaintBoundary(child: Spinner()),
  ],
);

Here expensiveMap is a widget that is costly to paint and never changes, and Spinner is a small animation that repaints on every frame. A RepaintBoundary gives its child a layer of its own. A test here lets the spinner run for ten frames and counts how often the map's painter is called: 11 times without the boundary, once with it.

Don't sprinkle boundaries everywhere; each one costs memory, and scrolling lists already add one per row. Turn on the repaint rainbow (below), look for a large area that flashes on every frame for no reason, and isolate the thing that is causing it.

3. Keep heavy work off the UI thread

Isolate comes from dart:isolate, so this file starts with import 'dart:isolate';. await does not help with work that is pure computation. This function has no await inside: once it starts, nothing else in your app runs until it returns, including the next frame.

primes.dart
// Plain CPU work: no awaits inside, so nothing else can run while it does.
int countPrimes(int limit) {
  var count = 0;
  for (var n = 2; n < limit; n++) {
    var isPrime = true;
    for (var d = 2; d * d <= n; d++) {
      if (n % d == 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) count++;
  }
  return count;
}

// ✗ Runs on the UI thread. The app cannot draw a frame until it returns.
int countPrimesHere() => countPrimes(5000000);

// ✓ Runs on another isolate (another thread with its own memory).
//   The UI keeps animating; the result comes back as a Future.
Future<int> countPrimesInBackground() {
  return Isolate.run(() => countPrimes(5000000));
}

As a rough measure: in this page's test run (flutter test on a desktop computer, unoptimised debug code) countPrimes(5000000) took about 1.2 seconds. A phone is slower. Called from a button handler, that is about 70 missed frames in a row: the app freezes.

Dart's answer is the isolate: a second thread with its own memory. Isolate.run starts one, runs your function there, sends the result back and shuts the isolate down. Because isolates share no variables there are no data races to worry about; the price is that the arguments and the result are passed as messages, so the function should take plain data and return plain data.

Flutter also has compute(function, argument), an older helper that does the same job. Reach for an isolate when work takes more than a few milliseconds and involves no waiting: parsing a large JSON response, resizing an image, searching a big list, encryption.

4. Don't decode a poster for a thumbnail

An image is decoded to its full size in memory unless you say otherwise. A 4000 × 3000 photo takes about 48 MB decoded (4 bytes per pixel), even if you show it 100 pixels wide.

thumbnail.dart (inside a build method)
// The file may be 4000 px wide; this spot shows it 100 px wide.
// cacheWidth decodes it at that smaller size, saving memory.
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
return Image.network(
  url,
  width: 100,
  height: 100,
  fit: BoxFit.cover,
  cacheWidth: (100 * pixelRatio).round(),
);

cacheWidth asks for a smaller decode. Multiply by the device pixel ratio so the picture stays sharp on dense screens. Better still, have your server send thumbnails.

Measure before you fix

main.dart (debugging aids)
void main() {
  debugPrintRebuildDirtyWidgets = true; // log every widget that rebuilds
  debugRepaintRainbowEnabled = true; // tint each layer when it repaints
  runApp(
    const MaterialApp(
      showPerformanceOverlay: true, // the two frame-time graphs
      home: Scaffold(body: ReportScreen(points: [1, 2, 3])),
    ),
  );
}
ToolShows youUse it when
Performance overlay (showPerformanceOverlay: true)Two live graphs of frame times, one for the UI thread and one for the raster thread. A bar turns red when a frame goes over budgetSomething stutters and you need to know which side is slow
debugPrintRebuildDirtyWidgetsA log line for every widget that rebuilds (debug mode)You suspect too much is rebuilding
debugRepaintRainbowEnabled (import package:flutter/rendering.dart)Each layer gets a new tint every time it repaints (debug mode)You suspect too much is repainting
Flutter DevToolsA widget inspector (tap a widget on the phone, see it in the tree with its constraints and size), a frame chart, a CPU profiler, a memory view, a network logEverything else. Your editor opens it, or run dart devtools

A workable routine: reproduce the stutter in profile mode, look at the overlay to see which graph spikes, then open the DevTools frame chart on a bad frame. A tall UI bar means go to "rebuild less" or "isolates". A tall raster bar means the picture itself is expensive: look for large blurs, big semi-transparent areas, clipping with rounded corners over large surfaces, and oversized images.

Staff-level§19

Talking to the platform, and shipping

In one sentenceDart can't call the camera, and it doesn't need to. A plugin wraps the Kotlin and Swift for you, and when no plugin exists, a platform channel lets your Dart send a message to native code and wait for the answer.

Packages and plugins

You add code from pub.dev with flutter pub add <name>, which edits pubspec.yaml and downloads the package. This is the dependency block of the project all the code on this page lives in:

pubspec.yaml (part)
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  material_ui: ^1.11.0
  go_router: ^18.1.4
  http: ^1.6.0
  provider: ^6.1.5+1
  flutter_riverpod: ^3.5.0
  flutter_bloc: ^9.1.1
  shared_preferences: ^2.5.6

^1.6.0 means "1.6.0 or any later 1.x" (semantic versioning). The exact versions that were picked are recorded in pubspec.lock. A second block, dev_dependencies, lists packages that are only for development and tests and are not shipped (§16).

There are two kinds of package:

  • A Dart package is only Dart: http, go_router, provider. Hot reload picks it up.
  • A plugin also contains native code for each platform: camera, location, secure storage, in-app purchases. After adding one you need a full stop and flutter run, because the native shell has to be rebuilt (§02).

Before you write native code yourself, search pub.dev. For most phone features there is a maintained plugin.

A platform channel, end to end

When there is no plugin, you write the bridge yourself. A channel is a named pipe: Dart sends a method name and arguments, native code replies with a result or an error.

One call over a MethodChannel
Dart
invokeMethod
awaiting the Future
result arrives
native
handler reads the battery
The call is asynchronous on the Dart side: your UI keeps running while the native code works.

The Dart side. MethodChannel, PlatformException and MissingPluginException come from package:flutter/services.dart, which this file imports next to material_ui:

lib/battery.dart
class Battery {
  // The name is the only link to the native side. Both must spell it the same.
  static const _channel = MethodChannel('atlas.dev/battery');

  /// The battery level from 0 to 100, or null if the phone can't tell us.
  Future<int?> level() async {
    try {
      // Sends a message to native code and waits for the reply.
      return await _channel.invokeMethod<int>('getBatteryLevel');
    } on PlatformException catch (e) {
      debugPrint('Native code reported: ${e.message}');
      return null;
    } on MissingPluginException {
      return null; // nobody on the native side listens on this channel
    }
  }
}

static const _channel is a constant that belongs to the class (§04), and invokeMethod<int> carries a type argument: "the answer will be an int".

The Android side goes in the activity that flutter create generated, which starts out as the single line class MainActivity : FlutterActivity(). (This Kotlin and the Swift below are not compiled by this page's test project; the class and method names were checked against the engine source of Flutter 3.47.)

android/app/src/main/kotlin/…/MainActivity.kt
package com.example.my_app   // keep the line your generated file has

import android.os.BatteryManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
  override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "atlas.dev/battery")
      .setMethodCallHandler { call, result ->
        if (call.method == "getBatteryLevel") {
          val manager = getSystemService(BATTERY_SERVICE) as BatteryManager
          result.success(manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY))
        } else {
          result.notImplemented()
        }
      }
  }
}

The iOS side goes in ios/Runner/AppDelegate.swift, inside the method the template already contains:

ios/Runner/AppDelegate.swift (part)
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
  GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)

  let channel = FlutterMethodChannel(
    name: "atlas.dev/battery",
    binaryMessenger: engineBridge.applicationRegistrar.messenger())
  channel.setMethodCallHandler { call, result in
    if call.method == "getBatteryLevel" {
      UIDevice.current.isBatteryMonitoringEnabled = true
      result(Int(UIDevice.current.batteryLevel * 100))
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

The iOS simulator has no battery and reports a level of −1, so this returns −100 there. Try it on a real phone.

Read all three together and the contract is small:

  • The channel name must match exactly on every side. It is the only link between them.
  • Arguments and results are simple values: null, booleans, numbers, strings, lists and maps of those. No classes cross the border.
  • Three outcomes. result.success(value) completes the Dart Future. result.error(…) makes it throw a PlatformException. And if nothing is listening on that name, Dart throws MissingPluginException(No implementation found for method getBatteryLevel on channel atlas.dev/battery). The tests for this section produce all three with a fake native side.

That last exception is also what you see after adding a plugin and only hot restarting: the Dart half is new, the native half is not built yet.

Permissions

Dangerous features need the user's consent, and each platform wants it declared in its own file:

AndroidiOS
Declare<uses-permission android:name="android.permission.CAMERA"/> in android/app/src/main/AndroidManifest.xmlA key with a sentence for the user in ios/Runner/Info.plist, such as NSCameraUsageDescription
Ask at run timeYes, for sensitive permissionsYes; iOS shows your sentence in the prompt
If you forgetThe request fails or is denied silentlyThe app is terminated when it touches the feature

Plugins usually perform the run-time request for you, but you still have to add the manifest entry and the Info.plist text. Their README files list what is needed. And remember the INTERNET permission for Android release builds from §14.

Assets and fonts

Files you ship inside the app are declared in pubspec.yaml:

pubspec.yaml (part)
flutter:
  uses-material-design: true

  # Files to bundle with the app. A path ending in / means the whole folder.
  assets:
    - assets/images/
    - assets/config.json

  fonts:
    - family: Roboto
      fonts:
        - asset: assets/fonts/Roboto-Regular.ttf
        - asset: assets/fonts/Roboto-Bold.ttf
          weight: 700

rootBundle in the next snippet comes from package:flutter/services.dart, and jsonDecode from dart:convert:

lib/brand.dart
class Brand extends StatelessWidget {
  const Brand({super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Image.asset('assets/images/logo.png', width: 32, height: 32),
        const Text(
          'Atlas',
          style: TextStyle(fontFamily: 'Roboto', fontWeight: FontWeight.w700),
        ),
      ],
    );
  }
}

Future<String> loadApiBase() async {
  // rootBundle reads any file listed under `assets:` in pubspec.yaml.
  final text = await rootBundle.loadString('assets/config.json');
  final config = jsonDecode(text) as Map<String, dynamic>;
  return config['apiBase'] as String;
}

A file that exists on disk but is not listed under assets: is not in the app, and loading it fails at run time. YAML indentation matters here: assets: must be indented under flutter:. The tool rebuilds the bundle of assets on the next hot reload after pubspec.yaml changed; if a new image or font still doesn't appear, stop the app and run it again.

Configuration per build

lib/config.dart
// flutter run --dart-define=API_BASE=https://staging.example.com
const apiBase = String.fromEnvironment(
  'API_BASE',
  defaultValue: 'https://api.example.com',
);

--dart-define passes values in at build time; they become compile-time constants. Use it for things like the server address. It is not a place for secrets: anything compiled into an app can be extracted from it. For separate dev, staging and production apps that can be installed side by side, both platforms support flavors (flutter run --flavor staging), configured in the Android and Xcode projects.

Building for the stores

CommandProducesFor
flutter build apkan APKinstalling directly on Android devices, testers
flutter build appbundlean AABuploading to Google Play
flutter build ipaan IPA (macOS with Xcode only)TestFlight and the App Store

These build in release mode by default. Flags worth knowing, all checked against flutter build apk -h in 3.47:

FlagDoes
--build-name=1.2.0, --build-number=37Override the version: 1.2.0+37 line of pubspec.yaml. The name is shown to users; the stores require the number to go up with every upload
--flavor stagingBuild one flavor
--dart-define=KEY=valueCompile-time configuration (above)
--obfuscate --split-debug-info=build/symbolsRename identifiers in the compiled code and store the symbol files separately. Keep them: you need them (flutter symbolize) to read crash stack traces
--split-per-abiAPK only: one smaller APK per processor type instead of one big one

Both stores also require code signing: an upload keystore for Android, certificates and provisioning profiles managed by Xcode for iOS. That setup is done once per app, outside Dart, and each store's documentation walks you through it.

Practitioner§20

Flutter and React Native, side by side

In one sentenceBoth give you one codebase for iOS and Android. React Native keeps React and JavaScript and asks the platform to draw real native views. Flutter brings its own language and its own renderer and draws everything itself.

Neither choice is wrong, and plenty of large apps ship on each. The differences that matter all follow from that one sentence. React Native has its own deep-dive; this table is the short comparison from the Flutter side.

FlutterReact Native
LanguageDart (§03, §04)JavaScript or TypeScript
UI codeWidget classes, nested constructor callsReact components and JSX, with hooks
Who draws the pixelsFlutter's engine, on a canvas (§01)The operating system: your components become real native views
Look and feelIdentical on every device. Material and Cupertino widget sets imitate each platformThe platform's own controls, so it looks native by default and differs between iOS and Android
LayoutConstraints go down, sizes go up; Row, Column, Stack (§07)Flexbox, close to what you know from CSS
How your code runs in releaseCompiled ahead of time to machine code (§02)JavaScript run by Hermes (React Native's JavaScript engine), calling native code through JSI
Edit and seeHot reload (§02)Fast Refresh
Packagespub.devnpm, plus native modules
What you reuse from the webConcepts: components, state, asyncReact itself, your TypeScript, many JavaScript libraries, sometimes shared code
Platforms from the same projectAndroid, iOS, web, Windows, macOS, LinuxAndroid and iOS; other platforms through separate projects
Phone featuresPlugins, or a platform channel (§19)Native modules

How the same ideas are spelled

You have met each of these on this page already:

IdeaReact / React NativeFlutter
A piece of UIfunction componentStatelessWidget / StatefulWidget
Inputspropsconstructor parameters, read as widget.x in a State
Local stateuseStatefields in a State + setState (§08)
Run on mount, clean upuseEffect with cleanupinitState / dispose
Identity in listskey propkey: parameter (§09)
Value for the whole subtreeContextInheritedWidget (§10)
Long listsFlatListListView.builder (§11)
Skip re-rendering a childmemo compares propssame widget object: const (§09)

Choosing between them

F

Lean towards Flutter when

You want the same custom design on every platform, animation-heavy or highly branded UI, desktop apps or screens built into devices (car dashboards, kiosks) as well, or a team that is new to both and can pick freely.
R

Lean towards React Native when

Your team already lives in React and TypeScript, you share logic or people with a web app, or the app should look and behave exactly like each platform's native apps.
=

It doesn't decide

Performance for ordinary screens, access to phone features, store acceptance, testing. Both are good enough at all of these that other factors should make the choice.
Practitioner§21

Pitfalls: the bugs everyone writes once

Most of these were reproduced in this page's test project, and every error text is copied from a real run. Read the titles now and come back when you hit one.

01

“I set width: 100 and it fills the screen”

Cause: the parent passed tight constraints, so the child's own size is ignored. The screen itself, SizedBox, Expanded and list rows all do this.

Fix: put a widget in between that loosens them: Center, Align, or a Row/Column (§07).

02

Yellow and black stripes: “A RenderFlex overflowed by … pixels”

Cause: the children of a Row or Column need more room than it has. Rows and columns never shrink their children.

Fix: wrap the child that should give way in Expanded or Flexible; make long content scroll; use Wrap for chips (§07). When it appears only with the keyboard open, the screen needs a scroll view (§12).

03

“Vertical viewport was given unbounded height”

Cause: a ListView (or GridView) directly inside a Column. The column offers endless height and the list wants all of it.

Fix: wrap the list in Expanded. If the whole page should scroll as one, use a CustomScrollView with slivers instead of shrinkWrap: true (§07, §11).

04

“RenderFlex children have non-zero flex but incoming height constraints are unbounded”

Cause: an Expanded inside a Column that sits in a scroll view. "The rest of the height" has no meaning when the height is endless.

Fix: remove the Expanded and size that child explicitly, or don't scroll this screen (§07).

05

“setState() called after dispose()”

Cause: an await finished after the user left the screen, and the code after it touched a State that no longer exists. The same thing with context is flagged by the linter as "Don't use 'BuildContext's across async gaps".

Fix: after every await, if (!mounted) return; in a State, or if (!context.mounted) return; elsewhere (§08, §10).

06

The screen keeps flashing back to a spinner, and the server gets hammered

Cause: the Future is created inside build: FutureBuilder(future: api.fetch(), …). Every rebuild starts a new request.

Fix: create the Future once in initState and store it in a field (§14).

07

State ends up on the wrong list row, or resets when it shouldn't

Cause: Flutter matches old and new widgets by type and position. Reordered rows without keys keep the State of their old position. Wrapping a widget in a different parent on some rebuilds changes its position and drops its State.

Fix: key: ValueKey(item.id) on list items with state; keep the tree's shape the same between rebuilds (§09).

08

A timer or listener keeps running after the screen is closed

Cause: something was started in initState and never stopped. A controller, a Timer, a stream subscription or a FocusNode that is not disposed keeps its State alive: a memory leak, and often the cause of pitfall 05.

Fix: for everything you create or start, write the matching line in dispose() at the same moment (§08).

09

“Scaffold.of() called with a context that does not contain a Scaffold”

Cause: the context you used belongs to the widget that creates the Scaffold, so it sits above it. Lookups go up. The same mistake can also fail without any error: Theme.of(context) returns the outer theme.

Fix: move the code into its own widget, or wrap it in Builder to get a context below. For snack bars use ScaffoldMessenger.of(context) (§10).

10

“I changed the code, hot reloaded, and nothing changed”

Cause: hot reload keeps existing objects. Changes to initState, to the initial value of a global or static field, or to main() do not run again. Changes to native code (a new plugin, anything under android/ or ios/) are not Dart at all.

Fix: hot restart (R) for the first group, a full stop and flutter run for the second (§02).

11

The tap handler never fires

Cause: a GestureDetector around something that paints nothing (an empty SizedBox, a transparent gap). By default it only reacts where its child is hit.

Fix: behavior: HitTestBehavior.opaque, or use InkWell inside a Material surface (§12).

12

Works in debug, broken or different in release

Cause, network: the Android INTERNET permission is only in the debug manifest (§14). Cause, speed: debug mode is much slower than release, in both directions: don't optimise from debug numbers, and don't assume a release build is fine without running one (§18). Cause, errors: assertions and the red error screen exist only in debug.

Fix: add the permission; measure in profile mode; test a real release build on a real phone before shipping.

13

The app freezes for a moment

Cause: long synchronous work on the UI thread: a big jsonDecode, sorting or filtering thousands of items inside build, image processing. await does not help, because nothing in that work waits.

Fix: move it to another isolate with Isolate.run (§18), and never do it in build.

14

“Null check operator used on a null value”

Cause: a ! on something that was null after all. Each ! switches the compiler's protection off for that expression.

Fix: handle the null: ?., ??, or an if that lets Dart promote the type (§03). Keep ! for places where you can point at the line that guarantees the value.

15

“Incorrect use of ParentDataWidget”

return const Center(
  child: Expanded(child: Text('Hi')), // ✗ not directly inside a Row/Column
);

Cause: Expanded, Flexible and Spacer only mean something as a direct child of a Row or Column. (Positioned has the same rule with Stack.) The full message names the culprit: "The offending Expanded is currently placed inside a Center widget."

Fix: move the Expanded so that it sits directly in the children list of the Row or Column, with other wrappers inside it (§07).

16

“An InputDecorator, which is typically created by a TextField, cannot have an unbounded width”

return const Row(
  children: [
    Icon(Icons.search),
    TextField(), // ✗ a TextField wants all the width; a Row offers ∞
  ],
);

Cause: a TextField wants to be as wide as its parent allows, and a Row asks its plain children with no upper limit (§07). The same rule that makes long text overflow makes a text field fail.

Fix: wrap it in Expanded, as the search box in §08 does, or give it a fixed width with SizedBox.

return const Row(
  children: [
    Icon(Icons.search),
    Expanded(child: TextField()), // ✓ "the width that is left"
  ],
);
17

“setState() or markNeedsBuild() called during build”

class Total extends StatelessWidget {
  const Total({super.key, required this.items, required this.onTotal});

  final List<int> items;
  final ValueChanged<int> onTotal;

  @override
  Widget build(BuildContext context) {
    final total = items.fold(0, (sum, item) => sum + item);
    onTotal(total); // ✗ the parent's handler calls setState, during a build
    return Text('Total: $total');
  }
}

Cause: something in a build method (or in initState) made another widget call setState while Flutter was in the middle of building. Here a child reports a value to its parent from inside build. Calling showDialog or navigating from build produces the same error.

Fix: build only describes. Work shared values out higher up and pass them down. Start dialogs and navigation from event handlers (onPressed), not from build.

class BasketFixed extends StatelessWidget {
  const BasketFixed({super.key, required this.items});

  final List<int> items;

  @override
  Widget build(BuildContext context) {
    // ✓ Work the value out where both widgets can get it, and pass it down.
    final total = items.fold(0, (sum, item) => sum + item);
    return Column(
      children: [Text('Header says $total'), Text('Total: $total')],
    );
  }
}
18

The theme is ignored, or “The name 'Scaffold' is defined in the libraries …”

Cause: the project mixes package:flutter/material.dart and package:material_ui/material_ui.dart (§02). Both imports in one file give the "defined in the libraries" error. In two different files you get The argument type 'ThemeData' can't be assigned to the parameter type 'ThemeData?', or no error at all and widgets in the default purple.

Fix: search the project for package:flutter/material.dart; there must be no hits. Editors re-insert it through auto-import, so check after pasting code.

What this page did not cover

Four things every real app needs sooner or later. This page does not teach them; here is the first step for each, so you know what to search for.

Dark theme. Give MaterialApp a second theme and let it follow the phone's setting. Widgets that take their colours from Theme.of(context).colorScheme then adapt by themselves; widgets with hard-coded colours do not.

themed_app.dart
class ThemedApp extends StatelessWidget {
  const ThemedApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.teal,
          brightness: Brightness.dark,
        ),
      ),
      themeMode: ThemeMode.system, // follow the phone's light/dark setting
      home: const Scaffold(body: Center(child: Text('Hello'))),
    );
  }
}

Remembering things on the phone. State in memory is gone when the app is closed. For a few small values (a setting, a token, "has seen the intro") the usual tool is the shared_preferences plugin (flutter pub add shared_preferences; this page compiled against 2.5.6). For real data you want a database package such as sqflite or drift, which this page did not try.

lib/settings.dart
import 'package:shared_preferences/shared_preferences.dart';

class Settings {
  final _prefs = SharedPreferencesAsync(); // small key-value store on the phone

  Future<bool> darkMode() async => await _prefs.getBool('darkMode') ?? false;

  Future<void> setDarkMode(bool value) => _prefs.setBool('darkMode', value);
}

Accessibility. Flutter draws its own pixels, so it also builds its own description of the screen for screen readers. The Material widgets do this for you. Your part: give icon-only buttons a tooltip, give meaningful images a semanticLabel, and test with the phone's text size turned up, because that is where fixed heights overflow.

Translations. Flutter's own solution is the flutter_localizations package together with message files in lib/l10n/, from which the tool generates a class with one getter per message. Set it up before the app has two hundred hard-coded strings. With material_ui, the delegates that translate the built-in widgets (GlobalMaterialLocalizations) come from that package too.

Practitioner§22

Check yourself: predict what happens

Decide on an answer before you click. Every answer was confirmed by running the code, and each explanation names the section to reread. The code shown is the code from the earlier sections with the giveaway comments removed.

Question 1 of 10
final and const

Dart. What happens when this function runs?

void finalVsConst() {
  final cart = [1, 2];
  cart.add(3);

  const sizes = [1, 2];
  sizes.add(3);
}
Question 2 of 10
Null safety

stock is {'apple': 3}. Why does this compile, although stock[fruit] may be null?

String describe(Map<String, int> stock, String fruit) {
  final count = stock[fruit];
  if (count == null) return 'We do not sell $fruit';
  return count.isEven ? 'even' : 'odd';
}
Question 3 of 10
Sync, microtask, event

Dart. In which order are the letters added to out? (The last line only stores the result once everything else has run.)

String results = '';

void main() {
  final out = <String>[];
  out.add('A');
  Future(() => out.add('B'));
  scheduleMicrotask(() => out.add('C'));
  out.add('D');
  Future(() => results = out.join(' '));
}
Question 4 of 10
How big is the box?

This is the whole screen on a 360 × 640 phone. How big is the teal box?

return ListView(
  children: [Container(width: 100, height: 100, color: Colors.teal)],
);
Question 5 of 10
Will it overflow?

text is a sentence of 200 characters, on a 360-wide phone. What do you see?

return Row(
  children: [
    const CircleAvatar(child: Icon(Icons.person)),
    const SizedBox(width: 12),
    Text(text),
    const Icon(Icons.chevron_right),
  ],
);
Question 6 of 10
What gets rebuilt?

The user taps Refresh. Which Leaf.build methods run?

class Dashboard extends StatefulWidget {
  const Dashboard({super.key, required this.user, required this.footer});

  final String user;
  final Widget footer;

  @override
  State<Dashboard> createState() => _DashboardState();
}

class _DashboardState extends State<Dashboard> {
  int _refreshes = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Refreshed $_refreshes times'),
        const Leaf(label: 'const'),
        Leaf(label: widget.user),
        widget.footer,
        TextButton(
          onPressed: () => setState(() => _refreshes++),
          child: const Text('Refresh'),
        ),
      ],
    );
  }
}
Question 7 of 10
Swap without keys

Two tiles each keep a tap count in their State: “Ada: 3 taps” above “Grace: 0 taps”. The list of names is reversed and the parent rebuilds with this code. What is on screen?

for (final name in _names)
  CounterTile(name: name),
Question 8 of 10
The disappearing count

The counter shows 5. Then _highlight becomes true and this build method runs again. What does the counter show?

return _highlight
    ? const ColoredBox(color: Colors.yellow, child: Counter())
    : const Counter();
Question 9 of 10
Future in build

This build method runs when the screen opens, and three more times while it is open (the keyboard opens, the theme changes, a parent's setState hands it new arguments). How many requests does the app send in total?

return FutureBuilder<List<Todo>>(
  future: api.fetchTodos(),
  builder: (context, snapshot) {
    if (snapshot.connectionState != ConnectionState.done) {
      return const Center(child: CircularProgressIndicator());
    }
    return Text('${snapshot.data!.length} todos');
  },
);
Question 10 of 10
Hot reload

Your initState sets _count = 0. With the app running and showing 7, you change that line to _count = 100 and hot reload. What does the screen show?

Answered 0 of 10
Foundations§23

Cheat sheet

🎨
Flutter paints everything itselfWidgets are Dart descriptions drawn by Flutter's engine on a canvas. They are not the platform's native controls.
📐
Constraints go down, sizes go upThe parent sets limits, the child picks a size inside them, the parent places it. Layout errors are about unbounded limits.
🧱
Layout is widgets, not stylesPadding, SizedBox, Center, Row, Column, Expanded, Stack. Wrap to add behaviour.
🔁
setState marks, the next frame rebuildsState lives in a State object. Change fields inside setState; build runs again before the next frame.
🌳
Widgets are rebuilt, elements stayOld and new widgets are matched by type and key. Same type at the same spot keeps its State.
🧊
const is the cheap optimisationThe same widget object as last time is skipped entirely, with everything below it.
⏳
After await, check mountedif (!mounted) return; before setState; if (!context.mounted) return; before using context.
🧹
Create in initState, clean up in disposeControllers, timers, focus nodes, subscriptions. Futures too: never create one in build.

Dart, for JavaScript eyes

JavaScriptDart
let x = 1 / const x = 1var x = 1; / final x = 1; (and const x = 1; for compile-time constants)
x === yx == y (same object: identical(x, y))
`Hi ${user.name}`'Hi ${user.name}', or 'Hi $name' for a plain variable
null / undefinednull only; a type allows it only with ?: String?
a?.b, a ?? bthe same, plus a! ("I know it isn't null")
function f(a, { b = 1 } = {})int f(int a, {int b = 1}), called as f(2, b: 3)
(x) => x * 2(x) => x * 2 (one expression only; otherwise a { } body with return)
class A { constructor(x) { this.x = x } }class A { A(this.x); final int x; }
new A(1)A(1)
[1, ...more], cond && item[1, ...more, if (cond) item, for (final m in more) m * 2]
{ a: 1 } used as a dictionary{'a': 1} (a Map; read with map['a'])
array.map(f), array.filter(f)list.map(f).toList(), list.where(f).toList()
Promise<T>, async function f()Future<T>, Future<T> f() async
JSON.parse(s), JSON.stringify(x)jsonDecode(s), jsonEncode(x) from dart:convert
import { x } from "./todo.js"import 'todo.dart'; (everything public), import '…' show x;, import '…' as p;
static method, throw new Error()static method, throw Exception('…')
console.log(x)print(x); in Flutter debugPrint('$x')
_private by convention_private enforced: visible only in its own file
switch statementswitch (x) { pattern => value, … } as an expression

Widget catalogue

I need…Widget
The app and a screenMaterialApp, Scaffold, AppBar
Text, icon, imageText, Icon, Image.network, Image.asset
A buttonFilledButton, OutlinedButton, TextButton, IconButton, FloatingActionButton
Things in a lineRow, Column; Expanded / Flexible / Spacer inside them; Wrap to flow onto new lines
SpacePadding, SizedBox, the spacing: of a Row/Column
PositionCenter, Align, Stack + Positioned, SafeArea
DecorationContainer (colour, border, radius), Card, Divider
A list or gridListView.builder, ListView.separated, GridView.builder, ListTile
Mixed scrolling contentCustomScrollView with SliverAppBar, SliverList, SliverToBoxAdapter
Something tappableInkWell, GestureDetector
Text inputTextField, TextFormField inside a Form
Navigation chromeNavigationBar, TabBar + TabBarView, Drawer
FeedbackCircularProgressIndicator, SnackBar (through ScaffoldMessenger), showDialog + AlertDialog
ChoicesSwitch, Checkbox, DropdownButton, Slider
Shared stateChangeNotifier + ChangeNotifierProvider, context.watch<T>() / context.read<T>()
Async dataFutureBuilder, StreamBuilder, RefreshIndicator
Rebuild a small partValueListenableBuilder, ListenableBuilder, Builder, LayoutBuilder

The State lifecycle

OrderMethodDo
1initState()set up: controllers, timers, the first Future. Call super.initState() first
2didChangeDependencies()rarely: react to inherited data
3build()describe the UI. Nothing else
on a parent rebuilddidUpdateWidget(old) then build()compare widget with old
on setStatebuild()
lastdispose()undo everything from initState. Call super.dispose() last

Commands

CommandDoes
flutter doctorchecks your installation
flutter create my_appnew project
flutter pub add material_ui + dart fix --apply --code=migrate_design_widgetsswitch a new project to the material_ui package (§02)
flutter runbuild and start in debug mode; then r hot reload, R hot restart, q quit
flutter run --profile / --releasethe other build modes
flutter pub add <package>add a dependency
flutter pub getdownload what pubspec.yaml lists
dart format .format every file
flutter analyzelinter and type checker
flutter testunit and widget tests
flutter test integration_testintegration tests on a device
flutter build apk / appbundle / iparelease builds

Symptom → cause → fix

You see…Probably…Fix
A sized box fills the screentight constraints from the parentwrap in Center / Align (§07)
Yellow and black stripesRow/Column children don't fitExpanded, scroll, or Wrap (§07)
"unbounded height"ListView in a ColumnExpanded around the list (§07)
Screen doesn't updatea field changed outside setState, or notifyListeners() is missingcall it (§08, §15)
State on the wrong rowlist items without keyskey: ValueKey(id) (§09)
State resets unexpectedlythe widget's type or position in the tree changedkeep the tree shape stable (§09)
"setState() called after dispose()"no mounted check after awaitadd it (§08)
"does not contain a Scaffold" / wrong themecontext from above the widget you wantBuilder or extract a widget (§10)
Spinner comes back on every rebuildFuture created in buildcreate it in initState (§14)
Hot reload changes nothingchanged initState, a global, or non-Dart fileshot restart, or full restart (§02)
Tap does nothingGestureDetector over an empty areaHitTestBehavior.opaque (§12)
Stutter while scrollingeverything rebuilds, or heavy work on the UI threadconst, state lower, Isolate.run; measure in profile mode (§18)
No network in the Android release buildmissing INTERNET permissionadd it to the main manifest (§14)
"Incorrect use of ParentDataWidget"Expanded not directly inside a Row/Columnmove it (§21)
"cannot have an unbounded width"a TextField directly in a Rowwrap it in Expanded (§21)
Theme ignored, or "defined in the libraries …"both Material libraries in one projectone import everywhere (§02)
Finished reading?Mark it complete and it counts toward your tracks. Saved in this browser only.
Share this topicTo link one section, use the beside its heading.