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.
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.
The other two ways to build an app make the difference clear. Switch between them:
In Flutter everything on screen is a widgetWidgetA small immutable Dart object that describes one piece of the UI: a text, a button, a padding, a whole screen. Flutter's unit of UI, the way a component is React's. Widgets are cheap descriptions, not the things on screen.: 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 elementElement (React)A small, plain JavaScript object that describes one piece of UI: its type ("div" or a component function), its props and an optional key. JSX creates elements; it doesn't create DOM nodes. it returns. You will build screens by putting widgets inside widgets.
What you get, and what you give up
| You get | You 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 version | Your widgets are not the platform's native controlsNative controlA button, text field or list drawn by the operating system's own UI toolkit: UIKit or SwiftUI on iOS, Android Views or Jetpack Compose on Android. Flutter does not use them for its widgets; it paints its own.. A new look in the next iOS release does not appear in your app by itself |
| Hot reloadHot reloadWhile the app runs in debug mode, Flutter sends your changed source files into it, swaps the code and rebuilds the widgets, usually in under a second. The app keeps its state: the screen you were on, text you typed, counters.: save a file, see the change in under a second, keep the app's state | A 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 default | Platform features (camera, payments, Bluetooth) go through a pluginPluginA package that contains Dart code plus native Kotlin/Swift code, so Dart can use a phone feature: camera, location, secure storage. You call its Dart API; it talks to the platform for you. 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.
First pass: enough to build an app
Second pass: when you hit the problem
Before you ship
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.
Setup and your first run
flutter doctor, flutter create, cd, flutter run. After that you mostly press r.Install, then ask the doctor
Install the Flutter SDKFlutter SDKThe folder you download to build Flutter apps: the flutter command, the Dart language tools, the framework source and the engine. One install serves every project on your machine. 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 emulatorEmulator / simulatorA phone that runs as a window on your computer. Android calls it an emulator, Apple calls it a simulator. Good for development; test performance on a real phone., 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 builddoes 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 (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_appHere is what those files are. You will spend almost all your time in the first three.
| Path | What it is |
|---|---|
lib/main.dart | Your app. All your Dart code goes in lib/. |
pubspec.yaml | The project file: app name, version, packages, bundled images and fonts. Flutter's package.json. (pubspec.yamlpubspec.yamlThe project file that names your app, lists its packages (dependencies) and declares bundled files such as images and fonts. Flutter's package.json.) |
test/widget_test.dart | One example test (§16). |
analysis_options.yaml | Which lint rulesLint ruleOne check a linter performs, such as “don't call print” or “widget constructors need a key parameter”. flutter create turns on a recommended set through the flutter_lints package. the LinterLinterA tool (like ESLint or golangci-lint) that reads your code without running it and warns about likely bugs. 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 embedderEmbedderThe small native app (the android/ and ios/ folders) that hosts Flutter: it creates the window, starts the engine and passes touches, keyboard input and lifecycle events to it.). 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.lock | The exact package versions that were resolved, like package-lock.json. (LockfileLockfileA file that records the exact version (and a checksum) of every dependency, direct and transitive, so every install gets identical code: package-lock.json for npm, go.sum (with go.mod) for Go. Commit it.) 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 foundThe 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:
| Key | What the tool calls it | What it does |
|---|---|---|
r | Hot reload | Load your changed code into the running app. State is kept. |
R | Hot restart | Start your Dart code again from main(). State is lost. |
q | Quit | Stop the app on the device. |
d | Detach | Stop 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.
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:
main()is where the program starts, andrunApp(…)hands Flutter the first widget.- Everything is a class with a
buildmethod that returns more widgets, nested like JSX:Scaffold(appBar: …, body: Center(child: Column(children: […]))). setStatewraps the line that changes_counter. That call is what makes the number on screen update (§08).
Hot reload, hot restart, full restart
Hot reloadHot reloadWhile the app runs in debug mode, Flutter sends your changed source files into it, swaps the code and rebuilds the widgets, usually in under a second. The app keeps its state: the screen you were on, text you typed, counters. is the feature that makes Flutter pleasant to work in. It is close to hot module replacementHot module replacement (HMR)When you save a file, the dev server sends the browser just that changed module and swaps it into the running page without a full reload, so the app keeps its state (open dialogs, typed text, React state). 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.
1final String greeting = 'final v1'; // a global: set once, on first use2const String label = 'const v1'; // a compile-time constant34void main() {5 runApp(const App());6}78class App extends StatefulWidget {9 const App({super.key});1011 @override12 State<App> createState() => _AppState();13}1415class _AppState extends State<App> {16 int _count = 0; // state: lives in memory while the app runs17 late final Timer _timer;1819 @override20 void initState() {21 super.initState();22 _timer = Timer.periodic(const Duration(seconds: 1), (_) {23 setState(() => _count++);24 });25 }2627 @override28 void dispose() {29 _timer.cancel();30 super.dispose();31 }3233 @override34 Widget build(BuildContext context) {35 return Text(36 'build v1 · count $_count · $greeting · $label',37 textDirection: TextDirection.ltr,38 );39 }40}
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.| New code | Keeps app state | Runs main() and initState() again | Typical 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 VMDart VMThe program that runs Dart code in debug mode. It can compile code on the fly (JIT), which is why it can accept changed source files while the app runs., which compiles code while the app is running (JITJIT (just-in-time) compilationCompiling code to machine instructions while the program runs. Dart uses it in debug mode, which is what makes hot reload possible: new code can be loaded into the running app.). 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 (AOTAOT (ahead-of-time) compilationCompiling all the code to machine instructions before the app ships. Dart uses it for profile and release builds: fast startup and steady speed, but no new code can be loaded at run time, so no hot reload.). 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 assertionsAssertion (assert)A check that only runs in debug mode: assert(x != null). If it fails the app throws an error on the spot. Flutter uses thousands of them to catch mistakes early; they are removed from release builds., which is why a debug build feels slower than the real app will.
| Build modeBuild mode (debug / profile / release)How the app is compiled. Debug: slow but with hot reload, assertions and debugging tools. Profile: release speed plus just enough tooling to measure performance. Release: what you ship to users. | Command | For |
|---|---|---|
| Debug | flutter run | Development: hot reload, assertions, debugger. Slow. |
| Profile | flutter run --profile | Measuring performance on a real phone (§18). |
| Release | flutter 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 MaterialMaterial DesignGoogle's design system: a set of rules and ready-made components (buttons, app bars, dialogs) with a consistent look. Flutter has a full implementation, in the SDK and, since 2026, in the package material_ui; version 3 of the design (“Material 3”) is the default. 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 createwrites it, the analyzerAnalyzerThe Dart tool that reads your code without running it and reports type errors and lint warnings. It powers the red squiggles in your editor and the flutter analyze command. 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_routerswitched in version 18.0.0 andflutter_riverpodin 3.5.0; both now build their screens withmaterial_ui. Not every package has moved yet. - The two libraries contain classes with the same names that are different classes.
MaterialAppfrom one is notMaterialAppfrom the other, and the same goes forTheme,Scaffoldand 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_router18 no longer sees a Material app. It looks formaterial_ui'sMaterialApp, 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
ThemeDatais invisible to any widget that asksmaterial_uifor 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_widgetsThe 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.
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".
Dart for JavaScript developers, part 1: values and functions
null stops the build, before the app ever runs.The rest of this page is written in DartDartThe programming language Flutter apps are written in. It looks like a mix of JavaScript and Java: curly braces, classes, async/await, but with types that are checked before the program runs., 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 TypeScriptTypeScriptJavaScript with type annotations. A separate type-check step (tsc, or your editor) reports type mistakes; build tools usually just strip the types without checking them, so the browser runs plain JavaScript., most of this will feel familiar.
The first differences
| JavaScript | Dart |
|---|---|
| Runs from the top of the file | Starts at a function called main() |
| Semicolons are optional | Semicolons are required |
console.log(x) | print(x); in a Flutter app, debugPrint('…') |
let / const | var / final, plus a stronger const |
One number type | int and double |
`Hi ${name}` (backticks only) | 'Hi $name' or 'Hi ${user.name}' in ordinary quotes |
=== | == (there is no ===) |
null and undefined | only null |
function add(a, b) { … } | int add(int a, int b) { … } |
Promise | Future (§04) |
import { x } from "./file.js" | import 'file.dart'; (§04) |
A first program
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 typesStatic typingEvery variable has a type that is known before the program runs, so the compiler can reject mistakes such as passing a number where a String is expected. TypeScript adds this on top of JavaScript; Dart has it built in.: every variable has one type for its whole life. You rarely have to write it, because of type inferenceType inferenceThe compiler working out a type you didn't write. In var name = 'Ada' Dart infers String, and from then on name is a String just as if you had written it.: 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 JSONJSONJavaScript Object Notation: a text format for data, like {"id": 7, "tags": ["a"]}. Readable by humans and every language; the default body format for web APIs. (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:
finalfinal (Dart)A variable that can be assigned exactly once. The value may be computed at run time, and the object it points to may still change inside. This is what JavaScript calls const. 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 whatconstmeans in JavaScript.constconst (Dart)A value that is completely known when the code is compiled and can never change, all the way down. Two identical const values are one shared object. Stronger than JavaScript's const, which only stops reassignment. means "known completely when the code is compiled, and frozen all the way down". Aconstlist can never change.
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 safetySound null safetyDart's rule that a variable can only hold null if its type says so with a question mark (String?). The compiler then forces you to handle the null case before using the value, so “null is not an object” crashes mostly disappear.: 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 promotionType promotionAfter a check such as if (x == null) return; Dart treats x as the narrower type (String instead of String?) for the rest of that code path, with no cast needed., 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
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.
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):
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 closuresClosureA function that remembers the variables around where it was created, even after that outer function has returned. Both Go and JS have them.. An anonymous function is written without the function keyword:
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
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$nameinserts a variable. Anything more than a plain name needs braces:${user.length}.- Dart never converts between types for you.
'42' + 1is 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 withint.parse('42'),double.parse(…)orvalue.toString(). /always produces adouble, even for6 / 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.
Dart for JavaScript developers, part 2: classes, files, collections, async
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
finalfield is set once, by the constructor, and never again. - The constructor has the class's name. There is no
constructorkeyword.this.idin its parameter list means "take this argument and store it in the fieldid". - 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 getterGetterA method that is read like a field: todo.label instead of todo.label(). Declared with the get keyword..
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.constin front of the constructor allows callers to create compile-time constant objects (const Todo(…)), as long as every field isfinal.String get label => …is read astodo.label, without parentheses.
Step three, the complete class with JSON support, comes after maps, a little further down.
extends, implements, with
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:
extendsis InheritanceInheritanceMaking a class by extending another one (class Admin extends User), so it gets all the parent's fields and methods. Go doesn't have it on purpose., as in JavaScript: one parent class. Anabstract classcannot be created itself; it exists to be extended.@overridemarks a member that replaces the parent's.implementsmeans "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 interfaceInterfaceA list of method names (and their signatures) with no code. Any type that has those methods can be used wherever the interface is expected. In Go this happens automatically, without writing “implements”. this way (a class markedfinal,baseorsealedcannot, outside its own file). You'll mostly see it in tests, for fakesFakeA test double with a small working implementation, e.g. an in-memory map instead of a real database..withadds a mixinMixinA bundle of fields and methods that a class can add with the keyword with, without inheriting from it. A way to share code between classes that don't have a common parent.: a bundle of members that is not a parent. You'll writewith SingleTickerProviderStateMixinto 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 isruntimeTypeA property every Dart object has: the class the object actually is. Flutter compares it to decide whether an old and a new widget are the same kind.. 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:
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
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.0A staticstatic memberA field or method that belongs to the class itself, not to one object. You reach it as ClassName.name: Colors.teal, Theme.of(context). 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"
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 fileLibrary-private (_name)A name that starts with an underscore is visible only inside its own file (strictly: its library). Dart has no private keyword; the underscore is the access rule.. 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 importsimportThe line at the top of a file that makes another file's or package's public names usable in this file: import 'dart:async'; for a built-in library, import 'package:…'; for a package, import 'todo.dart'; for your own file.. All your code lives under lib/. Here is one file:
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 httpimport '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 with | Comes from | Examples |
|---|---|---|
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 path | Your 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:
// 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.
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:
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 finalasync, await and Future
A FutureFutureDart's Promise: an object that stands for a value that will arrive later, or an error. You get the value with await or .then(). is Dart's PromisePromiseAn object that stands for a value that isn't ready yet. Later it becomes either fulfilled (with a value) or rejected (with an error)., 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
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
}
}throwworks as in JavaScript, withoutnew. You can throw any object; by convention it is anExceptionor one of the ready-made error classes such asArgumentErrorandFormatException.try/catch (error)is the same too. The addition ison 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 thecatchpart out:on FormatException { … }.- The type of
errorin a plaincatchisObject, 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 failedassert.- An error thrown inside an
asyncfunction travels through the Future and is caught by atryaround theawait, as in JavaScript.
Enums, and the dot shorthand
enum Status { active, paused }
Status current = Status.active; // the full name
Status next = .paused; // dot shorthand: Dart knows a Status goes hereAn enumEnum (Dart)A type with a fixed list of named values: enum Status { active, paused }. Flutter uses enums for most options, such as MainAxisAlignment.center. 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.
Dart you will meet later: streams, records, patterns, equality
Stream: many values over time
A Future delivers one value. A StreamStreamA sequence of values that arrive over time: clicks, WebSocket messages, a countdown. A Future gives you one value later; a Stream gives you many. You listen to it, or loop over it with await for. 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).
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 generatorGenerator functionA JavaScript function declared with function*. Calling it doesn't run the body; it returns an iterator. Each call to next() runs the body until the next yield, which hands out one value and pauses. in JavaScript. You will consume streams far more often than you write them.
Records: a few values in parentheses
A recordRecordA small fixed bundle of values written in parentheses: (3, 'a') or (name: 'Ada', age: 36). Handy for returning two things from a function without declaring a class. Two records with equal fields are equal. bundles a few values without a class. Use it to return two things from a function:
(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
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 classSealed classA class whose full list of subclasses is known to the compiler (they must be in the same file). A switch over it must handle every subclass, or the code does not compile. they are how Dart models "one of these few shapes", for example the three states of a screen that loads data:
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.)
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
constvalues are the same object, because the compiler creates each distinct constant once. This is the property Flutter uses to skip rebuildingconstwidgets (§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:
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.
Everything is a widget
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 elementElement (React)A small, plain JavaScript object that describes one piece of UI: its type ("div" or a component function), its props and an optional key. JSX creates elements; it doesn't create DOM nodes., 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:
| Widget | Job |
|---|---|
MaterialApp | The root of a MaterialMaterial DesignGoogle's design system: a set of rules and ready-made components (buttons, app bars, dialogs) with a consistent look. Flutter has a full implementation, in the SDK and, since 2026, in the package material_ui; version 3 of the design (“Material 3”) is the default. app. Sets up the theme, navigation between screens, text direction and more. You have exactly one. |
ThemeData | Colours and text styles for everything below. ColorScheme.fromSeed derives a whole palette from one colour. Material 3 is the default look. |
ScaffoldScaffoldThe Material widget that gives one screen its standard structure: an app bar on top, a body, and optional extras such as a floating button, drawer, bottom navigation bar and snack bars. | The 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. |
AppBar | The bar at the top with a title and, on inner screens, a back arrow. |
Center, Text | Center 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 PropsPropsThe inputs a React component receives from its parent, like arguments to a function. A component shouldn't change its own 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:
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 compositionComposition (of widgets)Building a bigger widget by putting smaller widgets inside it as children, instead of extending a big base class. Want padding? Wrap the widget in a Padding widget., 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 theifandforfrom §04 work inside it.
Buttons, and passing functions
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
onClickin React. Its type is a function type, writtenvoid Function(): "a function with no parameters that returns nothing".VoidCallbackis a ready-made name for exactly that type. You will also seevoid Function(String)(takes a String) andFuture<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
onPressedisnullis disabled. There is no separatedisabledflag. Here the delete button is greyed out whenever the parent doesn't passonDelete.
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.
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 rebuildRebuildFlutter calling a build method again and comparing the widgets it returns with the previous ones, to find out what on screen has to change. 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:
include: package:flutter_lints/flutter.yaml
linter:
rules:
prefer_const_constructors: trueA 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
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(),
],
);
}
}| Need | Widgets |
|---|---|
| Text and pictures | Text, Icon(Icons.…), Image.network(url), Image.asset(path) (§19) |
| Buttons | FilledButton (the main action), ElevatedButton, OutlinedButton, TextButton, IconButton, FloatingActionButton |
| One row of a list | ListTile (leading icon, title, subtitle, trailing icon, onTap) |
| Grouping | Card, Divider |
| Waiting | CircularProgressIndicator, LinearProgressIndicator |
| Screen structure | Scaffold, AppBar, Drawer (§10), NavigationBar (§13) |
| Layout | Row, 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.
Layout: constraints go down, sizes go up
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 constraintsConstraints (BoxConstraints)Four numbers a parent hands to a child during layout: minimum and maximum width, minimum and maximum height. The child must pick a size inside those limits.: a minimum and a maximum width, and a minimum and a maximum height. Lengths are in logical pixelsLogical pixelFlutter's unit of length. One logical pixel is roughly the same physical size on every screen; a sharp phone screen uses 2 or 3 real pixels for each. A typical phone is 360 to 430 logical pixels wide., 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:
- TightTight constraintsConstraints where minimum and maximum are the same, so the child has no choice: “be exactly 360 wide and 640 tall”.: minimum equals maximum. "Be exactly this size." The child has no say.
- LooseLoose constraintsConstraints with a minimum of zero: “be any size you like, up to this maximum”.: the minimum is 0. "Be any size up to this."
- UnboundedUnbounded constraintsConstraints whose maximum is infinity: “be as long as you want”. Scrolling widgets give them along the scroll direction. A child that wants to fill all the space cannot work with them.: 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:
// 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.
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
widthandheightare 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, aRowor aColumn. - A widget with nothing in it and no size collapses to zero on an unbounded axis. If a
Containeror aSizedBox"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'swidthis 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 FlexboxFlexboxA CSS layout mode for arranging items in one direction (a row or a column), sharing space and aligning them.. If you have read CSS Layout → Flexbox you know the ideas already; only the names differ.
- The main axisMain axisThe direction a Row or Column lays its children out in: horizontal for a Row, vertical for a Column. is the direction the children are laid out in: horizontal for a
Row, vertical for aColumn. - The cross axisCross axisThe direction at right angles to the main axis: vertical for a Row, horizontal for a Column. is the other one.
| CSS Flexbox | Flutter | Notes |
|---|---|---|
display: flex; flex-direction: row | Row(children: […]) | Column for column |
justify-content | mainAxisAlignment | start, center, end, spaceBetween, spaceAround, spaceEvenly |
align-items | crossAxisAlignment | start, center, end, stretch. The default is center, not stretch |
flex: 1 | Expanded(child: …) | Expanded(flex: 2, …) for two shares |
gap: 12px | spacing: 12 | or a SizedBox(width: 12) between two children |
flex-wrap: wrap | use a Wrap widget | a Row never wraps |
flex-shrink | (nothing) | children are never squeezed; they overflow |
| (the container's own size) | mainAxisSize | max (fill the main axis, the default) or min (hug the children) |
MainAxisAlignment.start decides where the other 120 go. Across, the Row is only as tall as it needs to be (70).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 overflowOverflow (RenderFlex overflowed)Children of a Row or Column that need more room than there is. In debug mode Flutter paints yellow and black stripes over the edge and logs how many pixels did not fit. error, and Expanded is the usual cure.
Expanded, Flexible and Spacer
How a Row or Column shares out its main axis, in order:
- Each child that is not wrapped in
ExpandedorFlexibleis asked "how long do you want to be?", with no upper limit, and gets that length. - What is left over is divided among the
ExpandedandFlexiblechildren, in proportion to their flex factorFlex factorThe number in Expanded(flex: 2). Leftover space in a Row or Column is divided between flexible children in proportion to their flex factors. (1 unless you say otherwise).
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:
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.Expandedforces its child to fill its share exactly.Flexibleoffers the same share as an upper limit: the child may be smaller.Spacer()is anExpandedwith nothing in it. It soaks up empty space.
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),
],
);
}
}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:
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.
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:
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:
- Wrap the child that should give way in
Expanded(orFlexible). - If the content is really longer than the screen, make it scroll:
ListView, orSingleChildScrollViewaround aColumn(both are in §11). - For a
Rowof chips or tags, switch toWrap.
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.)
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')),
],
);
}
}| Widget | What it does | CSS you know |
|---|---|---|
Padding | Space around its child, inside itself | padding |
SizedBox | Forces a width and/or height; with no child, an empty gap | width / height |
Center, Align | Takes all the space it is offered and places the child inside it | place-items: center |
Container | A convenience widget: padding + margin + size + colour/border/radius in one | a styled div |
ConstrainedBox | Adds extra limits, such as a maximum width | max-width |
AspectRatio | Sizes the child to a width-to-height ratio | aspect-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).
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 areaSafe areaThe part of the screen not covered by the notch, the status bar, rounded corners or the home indicator. The SafeArea widget adds just enough padding to keep its child inside it..
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.
return Column(
children: [
const Text('Inbox'),
ListView(children: const [Text('one'), Text('two')]), // ✗ throws
],
);Vertical viewport was given unbounded height.A viewportViewport (scrolling)The window of a scrolling widget: the visible rectangle through which you see a part of longer content. 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:
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.
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).
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 builderBuilder (callback)A function you pass to a widget that returns a widget. Flutter calls it when it needs that piece: itemBuilder for one list row, builder for a route or for the current state of a Future. 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.
State: StatefulWidget, setState and the lifecycle
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:
Counteris the widget: the immutable configuration that the parent passes down. Its only job besides holdingstepis to create the State._CounterStateis the State: an ordinary object with ordinary fields (_count) and thebuildmethod. Flutter creates it once and keeps it for as long as aCounterstays at that spot in the tree.
What setState does
setStatesetStateThe method you call on a State object to say “I changed some fields, please rebuild me”. Flutter marks that part of the tree as needing a rebuild and calls build before the next frame. is the one way a State tells Flutter that it changed.
setState(() { _count += widget.step; }) does two things, in this order:
- It runs the function you gave it, immediately.
_counthas its new value beforesetStatereturns. - It marks this State as needing a rebuild and asks Flutter for a new FrameFrameOne complete picture shown on the screen. Smooth motion is many frames per second, each slightly different, like the pages of a flip book.. 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 useState | Flutter setState | |
|---|---|---|
| Where the value lives | In React, handed to you each render | In a field of your State object |
| Reading it right after setting | Still the old value in this render | Already the new value |
| Calls in one handler | Batched into one render | Each call marks the same State; one rebuild next frame |
| Needs an updater function for "old + 1"? | Yes (c => c + 1), because of snapshots | No. _count++ is always right |
| Mutating a list in state | Does not re-render | Works, 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:
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.What belongs where:
| Method | Called | Put here | React equivalent |
|---|---|---|---|
initState() | Once, when the State is created | Create controllers, start timers, start listening to things, kick off the first load | useEffect(…, []) 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 different | Only describe the UI | the function body |
didUpdateWidget(old) | When the parent rebuilds with a new widget for this State | React to a changed parameter: restart something if widget.id != old.id | an effect with [id] in its dependency array |
deactivate() | When the State is taken out of the tree, just before dispose | Almost never overridden | — |
dispose() | Once, when the State is removed for good | Cancel timers, stop listening, dispose controllers | the 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';:
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 controllerControllerA long-lived object that owns the state of a widget you can then drive from outside: TextEditingController (the text in a field), ScrollController (scroll position), AnimationController (an animation's progress). You create it, so you must dispose it.. 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.
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.
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:
setState(() => _saving = true);
await widget.save(); // the user may leave the screen while this runs
setState(() => _saving = false); // ✗ throws if this State was disposedIn 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 mountedmountedTrue while a State (or a BuildContext) is still part of the tree. After the widget has been removed it is false, and calling setState or using the context is an error. property that is true from before initState until dispose. Check it after every await, before you touch setState or context:
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… | React | Flutter |
|---|---|---|
| Remember a value | useState | a field in the State + setState |
| Run once when shown | useEffect(fn, []) | initState() |
| Clean up when removed | return a function from the effect | dispose() |
| React to a prop change | useEffect(fn, [prop]) | didUpdateWidget(old) and compare |
| Keep a value without re-rendering | useRef | a field you change without setState |
| Reach a child imperatively | ref | a controller, or a GlobalKey (§12) |
| Compute from state | calculate 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.
The three trees: widgets, elements, render objects
build 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 elementElement (React)A small, plain JavaScript object that describes one piece of UI: its type ("div" or a component function), its props and an optional key. JSX creates elements; it doesn't create DOM nodes., 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
1class _CounterState extends State<Counter> {2 int _count = 0; // state: lives in this object, survives rebuilds34 void _increment() {5 setState(() {6 _count += widget.step; // ← change fields inside setState7 });8 }910 @override11 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}
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.Three facts from that walkthrough are worth stating on their own:
- Calling
setStatedoes not rebuild anything by itself. It marks one element as dirtyDirty elementAn element that has been marked as needing a rebuild, for example by setState. On the next frame Flutter rebuilds exactly the dirty elements, top to bottom.. 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
Counteris 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
runtimeTypeand samekey? 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 keyKeyAn optional identity you give a widget (key: ValueKey(id)). When a parent rebuilds, Flutter matches old and new children by type and key; without a key it matches by type and position. 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):
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
// ✗ 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:
// ✓ 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.
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);
}
}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.footerwas created by the parent, which did not rebuild. Same object as last time: skipped.Leaf(label: widget.user)is created anew each timebuildruns. 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.
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++),
);
}
}The two versions differ by one argument:
for (final name in _names)
CounterTile(name: name), // ✗ matched by positionfor (final name in _names)
CounterTile(key: ValueKey(name), name: name) // ✓ matched by keyYou 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.
| Key | Identity comes from | Use it for |
|---|---|---|
ValueKey(todo.id) | a value: an id, a name | list items. The usual choice. |
ObjectKey(todo) | the object itself | items without an id, when each item is a distinct object |
UniqueKey() | nothing: unique every time it is created | forcing a reset. Create it once and store it; a new one in every build resets the State on every rebuild. |
GlobalKeyGlobalKeyA key that is unique across the whole app. It lets you reach a widget's State from outside (formKey.currentState) and lets a widget keep its state when it moves to another parent. More expensive than other keys; use sparingly. | the key object, across the whole app | reaching a State from outside (formKey.currentState, §12), or moving a widget between parents with its State |
BuildContext is the element
BuildContextBuildContextA handle on one widget's place in the tree, passed to every build method. You use it to look upwards: Theme.of(context), Navigator.of(context). Under the hood it is that widget's Element. 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 elementElementThe long-lived object Flutter creates for each widget placed in the tree. It remembers the current widget at that spot, the State (if any) and the children. Elements are what persist between rebuilds; BuildContext 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
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 nearestTheme(yourMaterialAppputs 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.ofis 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:
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.
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:
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.
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 barSnack barA short message that slides up from the bottom of the screen and disappears by itself after a few seconds. The web calls it a toast. 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:
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.
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' checkA 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 InheritedWidgetInheritedWidgetA widget that offers a value to everything below it in the tree. Descendants read it through a static of(context) method and are rebuilt automatically when the value changes. Flutter's version of React context.. It is what React contextContext (React)A way to pass a value to every component below a Provider without threading it through props at each level. Components read it with useContext (or use() in React 19) and re-render when it changes. In React 19 you can write <MyContext value={…}> instead of <MyContext.Provider value={…}>. 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.
Lists and scrolling
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 virtualizationList virtualization (windowing)Rendering only the rows of a long list that are currently visible (plus a few extra), and swapping them as the user scrolls, so 10,000 items cost about as much as 20. when a list gets long. In Flutter it is how lists work from the start.
ListView, two ways
// 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)],
);// 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 created | Row build methods run | |
|---|---|---|
ListView(children: […]) | 10 000 | 16 |
ListView.builder(…) | 16 | 16 |
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 extentCache extentThe strip just outside a scrolling viewport in which Flutter keeps items built so they are ready when you scroll. 250 logical pixels before and after by default., so that a small scroll has nothing to wait for.
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
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
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 delegateDelegateA helper object that a widget asks for decisions, such as how many columns a grid has. 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
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
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 scrollableScrollableAny widget that scrolls: ListView, GridView, SingleChildScrollView, CustomScrollView., 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 FutureFutureDart's Promise: an object that stands for a value that will arrive later, or an error. You get the value with await or .then(). 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 sliversSliverA piece of a scrollable area that knows how to lay itself out lazily as it scrolls into view: a list, a grid, a collapsing header. ListView and GridView are slivers wrapped in a ready-made scroll view.: 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:
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.
User input and forms
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:
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'),
),
),
],
);
}
}InkWell | GestureDetector | |
|---|---|---|
| Feedback | Material's ripple (a circle of colour that spreads from your finger) and highlight | none |
| Gestures | tap, double tap, long press | those, plus drags, pans, scale (pinch) and more |
| Use for | rows, cards, anything that should feel like a button | swipes, custom controls, invisible tap areas |
If a list row should react to a tap, ListTile(onTap: …) already has the ripple built in.
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
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 inputControlled inputA form field whose value comes from React state (value={name}) and is updated in onChange. React is the source of truth, so every keystroke is a state update and a re-render., 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 controllerControllerA long-lived object that owns the state of a widget you can then drive from outside: TextEditingController (the text in a field), ScrollController (scroll position), AnimationController (an animation's progress). You create it, so you must dispose it., 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 keystroke | onChanged |
| Read the value when a button is pressed | a controller, then controller.text |
| Set or clear the text from code | a controller: controller.text = '…', controller.clear() |
| Validate several fields together | a 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.
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'),
],
);
}
}| Widget | For | Notes |
|---|---|---|
Switch, SwitchListTile | on / off | the …ListTile version adds a label and makes the whole row tappable |
Checkbox, CheckboxListTile | agree / select | onChanged gives a bool?, because a checkbox can have a third, "mixed" state |
DropdownButton<T> | one of a few options | T is the type of the values; items is a list of DropdownMenuItem |
Slider | a number in a range | §15 uses one |
showDatePicker, showTimePicker | dates and times | functions 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
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
FocusFocusWhich widget currently receives keyboard input. Giving a text field focus opens the on-screen keyboard; taking focus away closes it. 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:
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.
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.
Loading and sending data
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.6The file below imports dart:convert for jsonDecode, the http package under a prefix, and todo.dart, the file with the Todo class from §04.
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 builderBuilder (callback)A function you pass to a widget that returns a widget. Flutter calls it when it needs that piece: itemBuilder for one list row, builder for a route or for the current state of a Future. function. It calls the function with a snapshot of the Future's current state, and calls it again when that state changes.
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:
if returns the spinner.The snapshot has three things worth reading, and the order you check them in matters:
snapshot.connectionState:waitingwhile the Future runs,donewhen it has finished either way.snapshot.hasErrorandsnapshot.error.snapshot.hasDataandsnapshot.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
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:
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>);
}jsonEncodeisJSON.stringify. You give it aMap(or aList) of plain values and get a String.- The
Content-Typeheader tells the server the body is JSON. Without it many servers reject or misread the request. 201is the status for "created". Which status means success depends on the API; check it andthrowotherwise.- 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:
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 StreamStreamA sequence of values that arrive over time: clicks, WebSocket messages, a countdown. A Future gives you one value later; a Stream gives you many. You listen to it, or loop over it with await for. delivers many values (§05). StreamBuilder is the same idea as FutureBuilder, with the builder called once per value:
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):
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 loopEvent loopThe loop inside every JS runtime that repeatedly picks the next piece of waiting work (a callback) and runs it to completion on the single main thread. with the same two queues you may know from The Event Loop → Queues: a microtaskMicrotaskA tiny job (like a promise's .then callback or the code after an await) that JS runs right after the current code finishes, before timers, clicks or I/O. 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 (isolatesIsolateDart's unit of parallel work: a thread with its own separate memory. Isolates share no variables; they send each other messages. Your whole app normally runs in one isolate, and you start another for heavy computation., §18).
Sharing state between screens
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.
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 ListenableListenableAny object you can subscribe to with addListener and that calls you back when it changes. ChangeNotifier, ValueNotifier and animations are all Listenables.: any object you can subscribe to with addListener. The one you will use most is ChangeNotifierChangeNotifierA small class from Flutter that keeps a list of listeners and calls them when you call notifyListeners(). Extend it to make your own observable model, such as a shopping cart.. You extend it, keep your state in fields, and call notifyListeners() after each change:
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:
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, ValueNotifierValueNotifierA ChangeNotifier that holds exactly one value and notifies its listeners whenever you assign a different value to .value., with its own builder widget. It is handy for keeping a rebuild small inside a big screen:
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 providerprovider (package)A popular package that wraps InheritedWidget in a friendlier API: put an object above the widgets that need it, then read it with context.watch<T>() or context.read<T>(). 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.1The file needs import 'package:provider/provider.dart';, next to material_ui and your own cart.dart.
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 theCartonce, offers it to every widget below, and disposes it when it is removed. Put it aboveMaterialAppso that every screen can reach it.context.watch<Cart>()inbuild: find the nearestCartabove 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.
watchin a callback throws an error in debug mode;readinbuildcompiles, 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 InheritedWidgetInheritedWidgetA widget that offers a value to everything below it in the tree. Descendants read it through a static of(context) method and are rebuilt automatically when the value changes. Flutter's version of React context. mechanism from §10, and Flutter has a class that combines it with a notifier:
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'),
);
}
}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
RiverpodRiverpodA state management package where each piece of state is declared as a global provider object, outside the widget tree; the values themselves are kept in a ProviderScope at the top of the app. Widgets read them through a ref. Includes caching and loading/error handling for async data., 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.
// 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:
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.
// 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
BlocBloc / CubitA state management package built around streams of states. A Cubit is a class with methods that emit new state objects; a Bloc additionally takes events as input. The UI rebuilds for each emitted state. (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:
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
| Situation | Reach for |
|---|---|
| State used by one widget | setState |
| A couple of nearby widgets | lift it up, pass callbacks |
| One value that changes often inside a big screen | ValueNotifier + ValueListenableBuilder |
| Your first app, and most small apps | ChangeNotifier + provider |
| Lots of server data, caching, state that depends on other state | Riverpod |
| A large team that wants one enforced pattern and a record of every state change | Bloc |
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.
Testing: unit, widget and integration tests
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 pyramidTest pyramidA rule of thumb for mixing tests: many fast unit tests at the bottom, fewer integration tests in the middle, and a handful of slow end-to-end tests at the top., with an unusually good middle layer.
| Kind | Runs | Speed | Tests |
|---|---|---|---|
| Unit testUnit testA small automated test that checks one function or type on its own, usually in milliseconds, without real databases or networks. | plain Dart, no UI | milliseconds | models, parsing, business rules |
| Widget test | real widgets on a fake screen, no device | milliseconds to tens of ms | one widget or screen: what it shows, what a tap does |
| Integration test | the whole app on a device or emulator | seconds to minutes | critical 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 CIA 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.
// 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');
});// 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.
// 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:
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutterimport '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 emulatorKeep integration tests for the handful of flows that must never break (sign in, pay, the main screen loads), and for anything that involves a pluginPluginA package that contains Dart code plus native Kotlin/Swift code, so Dart can use a phone feature: camera, location, secure storage. You call its Dart API; it talks to the platform for you., which widget tests cannot run. The general ideas behind all three kinds are in Unit Testing and End-to-End Testing.
Putting it together: a Notes app in seven files
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 httpThen 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.
| File | What it holds | From |
|---|---|---|
lib/note.dart | the Note class with fromJson | §04 |
lib/notes_api.dart | NotesApi: every HTTP call | §14 |
lib/notes_model.dart | NotesModel: the shared state, a ChangeNotifier | §15 |
lib/main.dart | main(), the provider, the router | §13, §15 |
lib/notes_screen.dart | the list, with loading, error and empty states | §11, §14 |
lib/note_screen.dart | one note | §13 |
lib/new_note_screen.dart | the 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.
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./// 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:
new_note_screen.dart:_save()runs the validators, sets_saving, and callscontext.read<NotesModel>().add(…).notes_model.dart:addcalls_api.createNote(…)and waits.notes_api.dart:createNotesends thePOSTwith a JSON body, checks for status 201, and turns the answer into aNote.notes_model.dart: back inadd, the new note is put at the front of the list, andnotifyListeners()is called.notes_screen.dart: it calledcontext.watch<NotesModel>(), so it is rebuilt with the new list, although it is not even visible at this moment.new_note_screen.dart: theawaitis over. After themountedcheck,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 thehttp.Clientand theNotesApi. The provider creates theNotesModel. Nothing else in the app saysNotesApi(…)orhttp.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
ChangeNotifierProviderwrapsMaterialApp.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:
/// 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);
}
}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.
How a frame is made, and how to stay fast
One frame, step by step
The display sends a signal, vsyncVsyncThe signal from the display that it is about to show a new picture: 60 times a second on a 60 Hz screen, 120 on a 120 Hz one. Flutter starts work on a frame when it arrives., each time it is ready for a new picture. If something has changed, Flutter then produces a FrameFrameOne complete picture shown on the screen. Smooth motion is many frames per second, each slightly different, like the pages of a flip book.. The five phases below are simplified from the framework's own description of drawFrame, which lists ten:
- Animate. Every running animation controller moves forward one tick (§08).
- Build. Every dirtyDirty elementAn element that has been marked as needing a rebuild, for example by setState. On the next frame Flutter rebuilds exactly the dirty elements, top to bottom. element is rebuilt: your
buildmethods run (§09). - Layout. Render objects whose inputs changed work out their sizes: constraints down, sizes up (§07).
- 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 layersLayerA separately recorded piece of the picture. When something inside a layer changes, only that layer is repainted; the others are reused as they are and stacked together again..
- Raster. The finished layers are handed to the engine, which rasterizesRasterizeTurn drawing commands (“a rounded rectangle here, this text there”) into the actual coloured pixels of an image. them: the GPUGPUGraphics processor: a chip with thousands of small cores that run the same simple calculation in parallel. Browsers use it to draw and combine page layers; password crackers use it to test billions of fast hashes per second; AI models run on them because their maths is the same simple operations repeated billions of times. turns the commands into actual pixels.
Steps 1 to 4 are Dart, running on the UI threadUI threadThe thread that runs your Dart code: build methods, layout, event handlers (everything except code you start in another isolate). If your code keeps it busy too long, the app cannot produce the next frame.. Step 5 is the engine, on the raster threadRaster threadThe engine thread that takes the finished list of drawing commands for a frame and turns it into pixels with the GPU. None of your Dart code runs on it.. 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.
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.
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'),
),
],
);
}
}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.
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.
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 RepaintBoundaryRepaintBoundaryA widget that puts its child into its own layer, so repaints inside it do not force the surroundings to repaint, and the other way round. 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.
// 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 isolateIsolateDart's unit of parallel work: a thread with its own separate memory. Isolates share no variables; they send each other messages. Your whole app normally runs in one isolate, and you start another for heavy computation.: 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 racesData raceTwo threads or goroutines access the same memory, at least one of them writes, and nothing orders the two accesses (no lock, channel or atomic between them). The result is unpredictable. 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.
// 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
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])),
),
);
}| Tool | Shows you | Use 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 budget | Something stutters and you need to know which side is slow |
debugPrintRebuildDirtyWidgets | A 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 DevToolsFlutter DevToolsThe debugging and profiling tools that ship with the SDK and open in a browser or your editor: a widget inspector, a frame-time chart, a CPU profiler, a memory view and a network log. | A 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 log | Everything 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.
Talking to the platform, and shipping
Packages and plugins
You add code from pub.devpub / pub.devDart's package manager (the npm of Dart) and its public registry website, pub.dev. flutter pub add <name> adds a package; flutter pub get downloads what pubspec.yaml lists. 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:
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 versioningSemantic versioning (semver)Version numbers shaped MAJOR.MINOR.PATCH, like 1.4.2. Bump MAJOR for breaking changes, MINOR for new features, PATCH for fixes. Ranges like ^1.4.0 mean “1.4.0 or any newer 1.x”.). 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.
The Dart side. MethodChannel, PlatformException and MissingPluginException come from package:flutter/services.dart, which this file imports next to material_ui:
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.)
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:
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 aPlatformException. And if nothing is listening on that name, Dart throwsMissingPluginException(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:
| Android | iOS | |
|---|---|---|
| Declare | <uses-permission android:name="android.permission.CAMERA"/> in android/app/src/main/AndroidManifest.xml | A key with a sentence for the user in ios/Runner/Info.plist, such as NSCameraUsageDescription |
| Ask at run time | Yes, for sensitive permissions | Yes; iOS shows your sentence in the prompt |
| If you forget | The request fails or is denied silently | The 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:
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: 700rootBundle in the next snippet comes from package:flutter/services.dart, and jsonDecode from dart:convert:
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
// 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 flavorsFlavorA named variant of the same app, such as dev, staging and production, each with its own app id, name, icon and server address, so they can be installed side by side. (flutter run --flavor staging), configured in the Android and Xcode projects.
Building for the stores
| Command | Produces | For |
|---|---|---|
flutter build apk | an APKAPK / AAB / IPAThe file formats of a built app. APK: an Android app you can install directly. AAB (Android App Bundle): what you upload to Google Play, which builds per-device APKs from it. IPA: an iOS app archive for TestFlight and the App Store. | installing directly on Android devices, testers |
flutter build appbundle | an AAB | uploading to Google Play |
flutter build ipa | an 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:
| Flag | Does |
|---|---|
--build-name=1.2.0, --build-number=37 | Override 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 staging | Build one flavor |
--dart-define=KEY=value | Compile-time configuration (above) |
--obfuscate --split-debug-info=build/symbols | Rename 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-abi | APK only: one smaller APK per processor type instead of one big one |
Both stores also require code signingCode signingProving who built an app with a cryptographic key, which both stores require. On Android you create a keystore; on iOS Xcode manages certificates tied to your Apple developer account.: 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.
Flutter and React Native, side by side
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.
| Flutter | React Native | |
|---|---|---|
| Language | Dart (§03, §04) | JavaScript or TypeScript |
| UI code | Widget classes, nested constructor calls | React components and JSX, with hooks |
| Who draws the pixels | Flutter's engine, on a canvas (§01) | The operating system: your components become real native views |
| Look and feel | Identical on every device. Material and CupertinoCupertino widgetsFlutter's set of widgets that imitate Apple's iOS look (named after Apple's home town). An alternative to the Material widgets; both are drawn by Flutter itself. widget sets imitate each platform | The platform's own controls, so it looks native by default and differs between iOS and Android |
| Layout | Constraints go down, sizes go up; Row, Column, Stack (§07) | Flexbox, close to what you know from CSS |
| How your code runs in release | Compiled ahead of time to machine code (§02) | JavaScript run by Hermes (React Native's JavaScript engine), calling native code through JSIJavaScript bridge / JSIHow React Native's JavaScript reaches native code. The old bridge sent JSON messages back and forth; the current architecture uses JSI, which lets JavaScript call native functions directly. |
| Edit and see | Hot reload (§02) | Fast Refresh |
| Packages | pub.dev | npm, plus native modules |
| What you reuse from the web | Concepts: components, state, async | React itself, your TypeScript, many JavaScript libraries, sometimes shared code |
| Platforms from the same project | Android, iOS, web, Windows, macOS, Linux | Android and iOS; other platforms through separate projects |
| Phone features | Plugins, or a platform channel (§19) | Native modules |
How the same ideas are spelled
You have met each of these on this page already:
| Idea | React / React Native | Flutter |
|---|---|---|
| A piece of UI | function component | StatelessWidget / StatefulWidget |
| Inputs | props | constructor parameters, read as widget.x in a State |
| Local state | useState | fields in a State + setState (§08) |
| Run on mount, clean up | useEffect with cleanup | initState / dispose |
| Identity in lists | key prop | key: parameter (§09) |
| Value for the whole subtree | Context | InheritedWidget (§10) |
| Long lists | FlatList | ListView.builder (§11) |
| Skip re-rendering a child | memo compares props | same widget object: const (§09) |
Choosing between them
Lean towards Flutter when
Lean towards React Native when
It doesn't decide
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.
“I set width: 100 and it fills the screen”
Cause: the parent passed tightTight constraintsConstraints where minimum and maximum are the same, so the child has no choice: “be exactly 360 wide and 640 tall”. 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).
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).
“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).
“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).
“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).
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).
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).
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 leakMemory leakMemory that your program no longer needs but can't free, because something still holds a reference to it. In garbage-collected languages, a forgotten listener or map entry is the usual culprit., 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).
“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).
“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).
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).
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.
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.
“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.
“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).
“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"
],
);“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')],
);
}
}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.
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.
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.
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.
Dart. What happens when this function runs?
void finalVsConst() {
final cart = [1, 2];
cart.add(3);
const sizes = [1, 2];
sizes.add(3);
}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';
}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(' '));
}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)],
);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),
],
);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'),
),
],
);
}
}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),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();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');
},
);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?
Cheat sheet
Padding, SizedBox, Center, Row, Column, Expanded, Stack. Wrap to add behaviour.State object. Change fields inside setState; build runs again before the next frame.if (!mounted) return; before setState; if (!context.mounted) return; before using context.build.Dart, for JavaScript eyes
| JavaScript | Dart |
|---|---|
let x = 1 / const x = 1 | var x = 1; / final x = 1; (and const x = 1; for compile-time constants) |
x === y | x == y (same object: identical(x, y)) |
`Hi ${user.name}` | 'Hi ${user.name}', or 'Hi $name' for a plain variable |
null / undefined | null only; a type allows it only with ?: String? |
a?.b, a ?? b | the 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 statement | switch (x) { pattern => value, … } as an expression |
Widget catalogue
| I need… | Widget |
|---|---|
| The app and a screen | MaterialApp, Scaffold, AppBar |
| Text, icon, image | Text, Icon, Image.network, Image.asset |
| A button | FilledButton, OutlinedButton, TextButton, IconButton, FloatingActionButton |
| Things in a line | Row, Column; Expanded / Flexible / Spacer inside them; Wrap to flow onto new lines |
| Space | Padding, SizedBox, the spacing: of a Row/Column |
| Position | Center, Align, Stack + Positioned, SafeArea |
| Decoration | Container (colour, border, radius), Card, Divider |
| A list or grid | ListView.builder, ListView.separated, GridView.builder, ListTile |
| Mixed scrolling content | CustomScrollView with SliverAppBar, SliverList, SliverToBoxAdapter |
| Something tappable | InkWell, GestureDetector |
| Text input | TextField, TextFormField inside a Form |
| Navigation chrome | NavigationBar, TabBar + TabBarView, Drawer |
| Feedback | CircularProgressIndicator, SnackBar (through ScaffoldMessenger), showDialog + AlertDialog |
| Choices | Switch, Checkbox, DropdownButton, Slider |
| Shared state | ChangeNotifier + ChangeNotifierProvider, context.watch<T>() / context.read<T>() |
| Async data | FutureBuilder, StreamBuilder, RefreshIndicator |
| Rebuild a small part | ValueListenableBuilder, ListenableBuilder, Builder, LayoutBuilder |
The State lifecycle
| Order | Method | Do |
|---|---|---|
| 1 | initState() | set up: controllers, timers, the first Future. Call super.initState() first |
| 2 | didChangeDependencies() | rarely: react to inherited data |
| 3 | build() | describe the UI. Nothing else |
| on a parent rebuild | didUpdateWidget(old) then build() | compare widget with old |
on setState | build() | |
| last | dispose() | undo everything from initState. Call super.dispose() last |
Commands
| Command | Does |
|---|---|
flutter doctor | checks your installation |
flutter create my_app | new project |
flutter pub add material_ui + dart fix --apply --code=migrate_design_widgets | switch a new project to the material_ui package (§02) |
flutter run | build and start in debug mode; then r hot reload, R hot restart, q quit |
flutter run --profile / --release | the other build modes |
flutter pub add <package> | add a dependency |
flutter pub get | download what pubspec.yaml lists |
dart format . | format every file |
flutter analyze | linter and type checker |
flutter test | unit and widget tests |
flutter test integration_test | integration tests on a device |
flutter build apk / appbundle / ipa | release builds |
Symptom → cause → fix
| You see… | Probably… | Fix |
|---|---|---|
| A sized box fills the screen | tight constraints from the parent | wrap in Center / Align (§07) |
| Yellow and black stripes | Row/Column children don't fit | Expanded, scroll, or Wrap (§07) |
| "unbounded height" | ListView in a Column | Expanded around the list (§07) |
| Screen doesn't update | a field changed outside setState, or notifyListeners() is missing | call it (§08, §15) |
| State on the wrong row | list items without keys | key: ValueKey(id) (§09) |
| State resets unexpectedly | the widget's type or position in the tree changed | keep the tree shape stable (§09) |
| "setState() called after dispose()" | no mounted check after await | add it (§08) |
| "does not contain a Scaffold" / wrong theme | context from above the widget you want | Builder or extract a widget (§10) |
| Spinner comes back on every rebuild | Future created in build | create it in initState (§14) |
| Hot reload changes nothing | changed initState, a global, or non-Dart files | hot restart, or full restart (§02) |
| Tap does nothing | GestureDetector over an empty area | HitTestBehavior.opaque (§12) |
| Stutter while scrolling | everything rebuilds, or heavy work on the UI thread | const, state lower, Isolate.run; measure in profile mode (§18) |
| No network in the Android release build | missing INTERNET permission | add it to the main manifest (§14) |
| "Incorrect use of ParentDataWidget" | Expanded not directly inside a Row/Column | move it (§21) |
| "cannot have an unbounded width" | a TextField directly in a Row | wrap it in Expanded (§21) |
| Theme ignored, or "defined in the libraries …" | both Material libraries in one project | one import everywhere (§02) |