Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 73 ยท Practice and review

Flutter and Dart Cheat Sheet

A compact Flutter and Dart cheat sheet: CLI commands, common widgets, layout rules, state patterns, navigation, forms and async snippets, with links to lessons.

This page is a quick reference. It does not teach anything from scratch; every block links to the lesson that explains the idea. Keep it open while you code, and use it to jog your memory about a command, a constructor argument or a pattern.

Real vs stand-in. The commands and Dart snippets are real and read-only on this site. The live examples are small JavaScript stand-ins for the rules (layout clamping, flex sharing, async states), so you can check your understanding of the numbers.

Remember five rules

Constraints down Parents limit children.
Sizes up Children report a size.
Widgets are cheap Rebuild freely, keep build pure.
Notify setState or notifyListeners.
1 / 2

Commands

Terminal
flutter doctor                 # check the installation
flutter create my_app          # new project
flutter create --empty my_app  # minimal project
flutter run                    # run on a connected device (r = hot reload, R = hot restart)
flutter run -d chrome          # choose a device
flutter devices                # list devices
flutter pub add http           # add a package
flutter pub get                # fetch dependencies
flutter pub upgrade            # upgrade within constraints
flutter analyze                # static analysis
dart format .                  # format code
flutter test                   # run tests
flutter test --coverage        # with coverage
flutter build apk --release    # Android APK
flutter build appbundle        # Android App Bundle (Play Store)
flutter build ios              # iOS (macOS only)
flutter build web              # web
flutter clean                  # delete build output
flutter run --profile          # profile mode for performance work

See setup and publishing.

Dart essentials

DART
var name = 'Ada';            // inferred String
final started = DateTime.now(); // assigned once, at runtime
const pi2 = 3.14 * 2;           // compile-time constant
String? maybe;                  // nullable
late final String config;       // initialized later

print('Hello, $name! ${name.length} letters');

int add(int a, int b) => a + b;                        // arrow function
void greet({required String who, int times = 1}) {}    // named parameters

maybe?.length;          // null-aware call
maybe ?? 'default';     // fallback
maybe ??= 'set once';   // assign if null

Collections, spread and collection if/for:

DART
final nums = [1, 2, 3];
final more = [...nums, 4, if (nums.isNotEmpty) 5, for (final n in nums) n * 10];
final ages = {'Ana': 31, 'Bo': 28};
final tags = {'a', 'b'};

nums.where((n) => n.isOdd).map((n) => n * 2).toList();
nums.fold<int>(0, (sum, n) => sum + n);

final (x, y) = (3, 4);                      // record destructuring
final label = switch (x) { 0 => 'zero', > 0 => 'positive', _ => 'negative' };

Classes:

DART
class Point {
  const Point(this.x, this.y);
  final double x, y;
  Point.origin() : this(0, 0);
}

sealed class Shape {}
class Circle extends Shape { Circle(this.r); final double r; }
class Square extends Shape { Square(this.s); final double s; }

double area(Shape s) => switch (s) {
  Circle(:final r) => 3.14159 * r * r,
  Square(:final s) => s * s,
};

See Dart basics, null safety, classes and collections.

Widgets you use daily

Need Widget
Text, icon, image Text, Icon, Image.asset, Image.network
Vertical / horizontal line Column, Row
Share leftover space Expanded, Flexible, Spacer
Overlap Stack + Positioned / Align
Spacing and size Padding, SizedBox, ConstrainedBox, Container
Scrolling list ListView.builder, GridView.builder, CustomScrollView
Whole screen Scaffold (appBar, body, floatingActionButton)
Buttons FilledButton, ElevatedButton, TextButton, IconButton
Input TextField, TextFormField, Checkbox, Switch, Slider
Feedback SnackBar, AlertDialog, showModalBottomSheet
Tap GestureDetector, InkWell
Wrap long rows Wrap
DART
Scaffold(
  appBar: AppBar(title: const Text('Home')),
  body: ListView.builder(
    itemCount: items.length,
    itemBuilder: (context, i) => ListTile(title: Text(items[i])),
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: add,
    child: const Icon(Icons.add),
  ),
)

See widgets and the Material tour.

Layout rules

  • Constraints go down, sizes go up, parents set positions. (details)
  • Row and Column give children unbounded space on their main axis: use Expanded/Flexible for text or lists.
  • Put scrollables in a bounded space (Expanded, SizedBox), not directly in a Column.
  • Center and Align loosen constraints; SizedBox with both sizes makes them tight.
  • MainAxisAlignment spaces along the line; CrossAxisAlignment aligns across it.
  • Use LayoutBuilder for local width, MediaQuery for the screen. (responsive)
JS Stand-in: flex sharing of leftover space

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The 352 pixels left after the icon split 2:1, giving about 234.67 and 117.33. See Row, Column and Flex.

State patterns

DART
// Local state
class _CounterState extends State<Counter> {
  int n = 0;
  @override
  Widget build(BuildContext context) =>
      TextButton(onPressed: () => setState(() => n++), child: Text('$n'));
}

// ValueNotifier
final count = ValueNotifier(0);
ValueListenableBuilder<int>(
  valueListenable: count,
  builder: (_, v, __) => Text('$v'),
);

// ChangeNotifier + Provider
class Cart extends ChangeNotifier {
  final items = <String>[];
  void add(String s) { items.add(s); notifyListeners(); }
}
context.watch<Cart>();                       // rebuild on change
context.read<Cart>().add('x');               // action, no subscription
context.select<Cart, int>((c) => c.items.length);
Scope Tool
One widget setState
A subtree lift state up, ValueNotifier, InheritedWidget
Whole app Provider, Riverpod, BLoC/Cubit

Rules: change state only through setState or notifyListeners; dispose controllers, timers and subscriptions in dispose(). See setState, lifting state, Provider, Riverpod, BLoC.

DART
// Navigator 1.0
Navigator.of(context).push(MaterialPageRoute(builder: (_) => const Detail()));
final result = await Navigator.of(context).push<bool>(...);
Navigator.of(context).pop(true);

// go_router
final router = GoRouter(routes: [
  GoRoute(path: '/', builder: (c, s) => const Home(), routes: [
    GoRoute(path: 'item/:id', builder: (c, s) => Item(id: s.pathParameters['id']!)),
  ]),
]);
MaterialApp.router(routerConfig: router);
context.go('/item/7');      // replace the location
context.push('/item/7');    // add on top
context.pop();

See Navigator and go_router.

Forms

DART
final key = GlobalKey<FormState>();
Form(
  key: key,
  child: TextFormField(
    controller: controller,
    keyboardType: TextInputType.emailAddress,
    autovalidateMode: AutovalidateMode.onUserInteraction,
    validator: (v) => (v ?? '').contains('@') ? null : 'Invalid email',
  ),
);
if (key.currentState!.validate()) { /* submit */ }

A validator returns null when the value is valid. See forms.

Async snippets

DART
Future<String> load() async {
  try {
    final response = await http.get(Uri.parse('https://example.com/data'));
    if (response.statusCode != 200) throw Exception('HTTP ${response.statusCode}');
    return response.body;
  } on SocketException {
    rethrow;
  } finally {
    // cleanup
  }
}

final results = await Future.wait([a(), b()]);      // run together
final value = await Future.value(1).timeout(const Duration(seconds: 5));

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

await for (final t in ticks()) { print(t); }
final big = await Isolate.run(() => heavyParse(text)); // off the UI isolate

After any await in a State, check if (!mounted) return; before setState or using context.

DART
FutureBuilder<String>(
  future: _future,   // created once, in initState
  builder: (context, snap) {
    if (snap.connectionState != ConnectionState.done) return const CircularProgressIndicator();
    if (snap.hasError) return Text('${snap.error}');
    return Text(snap.data!);
  },
)
JS Stand-in: Future.wait vs sequential awaits

Press Run (or Ctrl + Enter) to see the console output here.

No output.

See async Dart, HTTP and JSON and FutureBuilder.

Performance and quality checklist

  • Add const to constructors and widgets wherever possible.
  • Use ListView.builder for long lists; give list items stable ValueKeys.
  • Keep build free of network calls, sorting and parsing.
  • Profile with flutter run --profile and DevTools, not in debug mode. (performance)
  • Dispose controllers; check mounted after awaits. (common mistakes)
  • Test logic with unit tests and screens with testWidgets. (testing)

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which command checks that your Flutter installation is healthy?

    flutter doctor reports missing SDKs, licenses and devices; analyze checks your code.
  2. 2. Which call runs an action in a callback without subscribing the widget to rebuilds?

    read fetches the object once; watch and select subscribe, and Provider.of defaults to listening.
  3. 3. In a Row with a 48 px icon and two Expanded children of flex 2 and 1 in 400 px, how wide is the flex 1 child (about)?

    352 px are left after the icon, shared 2:1, so the flex 1 child gets about 117 px.

Summary

  • Know your daily commands: run, pub add, analyze, test, build.
  • Layout is constraints down, sizes up; Expanded and bounded scrollables fix most errors.
  • Pick state tools by scope, and always notify and dispose.
  • Create futures once, and guard await with mounted.

You have reached the end of the track. To revisit a topic, start again at What Is Flutter?.