Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 61 ยท Practice and Review

Dart Cheat Sheet

A one-page Dart cheat sheet: variables, null safety, strings, collections, functions, classes, patterns, async, streams and everyday commands, with short examples.

This page is a quick reference for the Dart you write most often. It is not a tutorial: every block assumes you have seen the idea before and just need the syntax back in front of you. Each section links to the lesson that explains the topic in depth. All Dart code is read-only on this site; two small TypeScript stand-ins at the end let you run the closest equivalents.

Bookmark it, and use your browser's search (Ctrl+F) to jump to what you need.

Program structure and comments

DART
import 'dart:math';                 // core libraries: dart:math, dart:async, dart:convert, dart:io
import 'package:http/http.dart' as http;   // a package, with a prefix

/// A documentation comment (shown by tools).
// A line comment
/* A block comment */

void main(List<String> args) {      // the entry point; args are the command-line arguments
  print('Hello, ${args.length} args');
}

See Your First Dart Program.

Variables and constants

DART
var name = 'Ada';              // type inferred: String
String city = 'London';        // explicit type
int count = 0;
double ratio = 0.5;
bool done = false;
num any = 3;                   // int or double

final started = DateTime.now();  // assigned once, at runtime
const maxUsers = 100;            // compile-time constant
late String token;               // assigned later, before first read
late final big = expensive();    // computed lazily on first read

final stops reassignment, const makes a deeply immutable compile-time value. See Variables, var, final and const.

Numbers and operators

DART
7 / 2        // 3.5 (always a double)
7 ~/ 2       // 3   (integer division)
7 % 3        // 1   (remainder, never negative)
2 + 3 * 4    // 14
x++; x += 2; // increment, compound assignment

int.parse('42');                    // throws FormatException if invalid
int.tryParse('x');                  // null if invalid
double.parse('3.14');
3.7.round(); 3.2.ceil(); 3.9.floor(); 3.9.truncate();
(3.14159).toStringAsFixed(2);       // '3.14'

Comparison: == != < > <= >=. Logic: && || !. Bitwise: & | ^ ~ << >>. Type tests: is, is!, as. See Numbers and Booleans and Operators.

Null safety

DART
String  a = 'x';        // can never be null
String? b;              // may be null (default null)

b?.length               // null if b is null
b ?? 'default'          // fallback
b ??= 'set once';       // assign if null
b!                      // assert non-null (throws if wrong)
b?..toString();         // null-aware cascade
if (b != null) { b.length; }   // type promotion on locals

Fields and top-level variables are not promoted by a null check; copy to a local first. See Null Safety.

Strings

DART
'single', "double", '''multi
line''', r'raw \n not escaped'
'Hello, $name! ${1 + 2} items'      // interpolation
'a' 'b'                             // adjacent literals join: 'ab'

s.length; s.isEmpty; s.isNotEmpty;
s.toUpperCase(); s.trim(); s.substring(1, 3);
s.contains('x'); s.startsWith('a'); s.indexOf('b');
s.replaceAll('a', 'b'); s.split(','); s.padLeft(5, '0');
s[0]; s * 3;                        // index and repeat
final buf = StringBuffer()..write('a')..write('b');   // efficient building

See Strings.

Control flow

DART
if (x > 0) { ... } else if (x == 0) { ... } else { ... }
final label = x > 0 ? 'positive' : 'not positive';

for (var i = 0; i < 3; i++) {}
for (final item in items) {}
while (cond) {}
do { } while (cond);
outer: for (...) { for (...) { continue outer; } }   // labels

final size = switch (n) { < 10 => 'small', < 100 => 'medium', _ => 'large' };

switch (cmd) {
  case 'go': run();
  case 'stop' || 'halt': stop();
  default: print('?');
}

Dart switch cases do not fall through; no break is needed. See Conditionals, Loops and switch.

Functions

DART
int add(int a, int b) => a + b;                       // arrow body
void log(String msg, [String level = 'info']) {}      // optional positional
void send({required String to, int retries = 3}) {}   // named
(int, String) pair() => (1, 'one');                   // record return

final square = (int n) => n * n;                      // function value
typedef Predicate<T> = bool Function(T);              // function type alias
items.map(square);                                    // tear-off: pass by name
Function counter() { var c = 0; return () => ++c; }   // closure

See Functions, Parameters and First-Class Functions.

Collections

DART
final list = <int>[1, 2, 3];
final set = <String>{'a', 'b'};
final map = <String, int>{'a': 1, 'b': 2};

list.add(4); list.addAll([5, 6]); list.removeAt(0); list.insert(0, 9);
list.sort((a, b) => b.compareTo(a));
list.first; list.last; list.length; list.contains(3); list.indexOf(3);
list.sublist(1, 3);

map['c'] = 3;
map.putIfAbsent('d', () => 4);
map.update('a', (v) => v + 1, ifAbsent: () => 1);
map.containsKey('a'); map.remove('a');
for (final e in map.entries) { print('${e.key}: ${e.value}'); }

final all = [...list, ...[7, 8]];                     // spread
final withOpt = [1, if (flag) 2, for (var i in xs) i * 2];   // collection if/for

See Lists, Sets and Maps.

Iterable methods

DART
xs.map((x) => x * 2)           // lazy
xs.where((x) => x.isEven)      // lazy
xs.fold<int>(0, (a, b) => a + b)
xs.reduce((a, b) => a + b)     // throws on empty
xs.any((x) => x > 3); xs.every((x) => x > 0);
xs.expand((x) => [x, x]);      // flatMap
xs.take(2); xs.skip(2); xs.toList(); xs.toSet();
xs.firstWhere((x) => x > 1, orElse: () => -1);
xs.followedBy(ys); xs.reversed;

Iterables are lazy; call toList() to run the pipeline once and keep the result. See Iterables.

Records and patterns

DART
var point = (x: 1, y: 2);               // record with named fields
final (a, b) = (1, 'one');              // destructure
final {'id': id, 'name': name} = json;  // map pattern (throws if no match)
if (json case {'id': int id}) { print(id); }   // if-case

switch (shape) {
  case Circle(radius: var r): ...
  case Square(:var side) when side > 0: ...
}

See Records and Patterns and Destructuring.

Classes

DART
class Point {
  const Point(this.x, this.y);              // const constructor, initializing formals
  Point.origin() : x = 0, y = 0;            // named constructor with initializer list
  factory Point.fromList(List<int> v) => Point(v[0], v[1]);

  final int x, y;
  double get length => sqrt(x * x + y * y); // getter
  Point operator +(Point o) => Point(x + o.x, y + o.y);

  @override
  bool operator ==(Object other) => other is Point && other.x == x && other.y == y;
  @override
  int get hashCode => Object.hash(x, y);
  @override
  String toString() => 'Point($x, $y)';
}

static const zero = Point(0, 0);   // inside a class: static member
String _private;                   // underscore: private to the library

See Classes, Constructors and Operator Overloading.

Inheritance, interfaces and mixins

DART
abstract class Animal { String speak(); }              // abstract members
class Dog extends Animal { @override String speak() => 'Woof'; }
class Fake implements Animal { @override String speak() => '...'; }

mixin Swimmer { void swim() => print('splash'); }
class Duck extends Animal with Swimmer { ... }
mixin Logger on Service { }                            // restricted to Service subtypes

extension StringTools on String { bool get isBlank => trim().isEmpty; }

See Inheritance, Abstract Classes and Interfaces, Mixins and Extension Methods.

Class modifiers (Dart 3)

Modifier Outside its library you can...
abstract extend and implement; cannot instantiate
base extend (subtypes must be base/final/sealed), not implement
interface implement, not extend
final neither extend nor implement
sealed nothing; subtypes are closed and switches are exhaustive
mixin class use as both a class and a mixin

See Class Modifiers.

Enums and generics

DART
enum Status { active, blocked }
enum Level {
  low(1), high(3);
  const Level(this.weight);
  final int weight;
}
Status.values; Status.active.name; Status.values.byName('blocked');

class Box<T extends Comparable<T>> {
  Box(this.value);
  final T value;
}
T first<T>(List<T> xs) => xs.first;

See Enums and Generics.

Exceptions

DART
try {
  risky();
} on FormatException catch (e) {
  print(e.message);
} on Exception {
  rethrow;
} catch (e, stackTrace) {
  print('$e\n$stackTrace');
} finally {
  cleanup();
}

throw ArgumentError('bad value');
assert(x > 0, 'x must be positive');   // only checked in debug mode

Exception is for recoverable problems, Error for bugs. See Exceptions.

Futures

DART
Future<String> load() async {
  await Future<void>.delayed(const Duration(seconds: 1));
  return 'data';
}

final value = await load();
final both = await Future.wait([load(), load()]);
load().then((v) => print(v)).catchError((e) => print(e));
await load().timeout(const Duration(seconds: 2), onTimeout: () => 'late');

See Futures and async/await.

Streams

DART
Stream<int> count(int n) async* {
  for (var i = 1; i <= n; i++) { yield i; }
}

await for (final v in count(3)) { print(v); }
count(3).where((v) => v.isOdd).map((v) => v * v).listen(print);

final controller = StreamController<String>();      // .broadcast() for many listeners
controller.add('event');
await controller.close();

See Streams and The Event Loop.

Isolates, JSON and files

DART
final result = await Isolate.run(() => heavyComputation());   // dart:isolate

import 'dart:convert';
final data = jsonDecode('{"a": 1}') as Map<String, Object?>;
final text = jsonEncode({'a': 1});

import 'dart:io';
final file = File('notes.txt');
await file.writeAsString('hello');
final lines = await file.readAsLines();
stdout.writeln('output'); final input = stdin.readLineSync();

See Isolates, JSON and Serialization and Files and Command-Line Programs.

Everyday commands

TEXT
dart create -t console my_app   # new project (also: package, server-shelf)
dart run                        # run bin/main.dart
dart pub add http               # add a dependency
dart pub get                    # fetch dependencies
dart analyze                    # static analysis (lints)
dart format .                   # format code
dart test                       # run tests (package:test)
dart compile exe bin/main.dart  # native executable
dart compile js bin/main.dart   # JavaScript

See Installing the Dart SDK and Libraries and Packages.

Try the nearest equivalents

The closest TypeScript equivalents let you play with a few of these idioms. The first covers the collection syntax and iterable pipeline:

TypeScript Collections and pipelines (TypeScript stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The second shows futures and streams with Promises and async generators:

TypeScript Async and streams (TypeScript stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which expression gives 3 for 7 and 2?

    ~/ is truncating integer division. / gives the double 3.5, % gives the remainder 1, and // is not a Dart operator.
  2. 2. How do you declare a named parameter that callers must provide?

    Named parameters go in braces, and the required keyword makes them mandatory.
  3. 3. Which line safely reads the length of a String? s, falling back to 0?

    ?. returns null when s is null, and ?? then supplies the fallback.

Summary

  • var, final, const and late cover every variable situation; prefer final and const.
  • Types are non-nullable by default; use ?, ?., ??, ??= and null checks instead of !.
  • Collections support literals, spread, collection if and for, and lazy iterable methods.
  • Classes use initializing formals, named, factory and const constructors; Dart 3 modifiers control how types may be extended.
  • Records, patterns and switch expressions make branching on data concise and exhaustive.
  • Future with async/await, Stream with async* and await for, and Isolate.run cover asynchronous and parallel work.

You have reached the end of the tutorial. Revisit What Is Dart? any time, or test yourself again with the Dart Interview Questions.