Skip to main content
Quick Reference

Dart Cheatsheet

Dart 3 on one page — null safety, types, operators, control flow, functions, collections, classes and mixins, records and sealed types, Futures, and the traps that show up in Flutter interviews.

10 sections 9 tables 20 code snippets

Program & the Dart CLI

Smallest program

void main() {
  const name = "Ravi";
  print("Hello, $name");
}

Create, run, check

dart create hello
dart run
dart analyze
dart format .
dart test

Where a name lives

FormMeaning
varType is inferred. You can assign again
finalOne assignment. The value can be computed at runtime
constA compile-time constant. The object is canonicalized
lateInitialized later. Reading it too early throws
dynamicTurns static checks off. Avoid it

Dart is null-safe. A String cannot hold null. A String? can. Flutter UI is Dart, so these rules apply in every widget.

Types & Null Safety

Common types

int n = 42;
double price = 19.5;
num either = 3;
bool ok = true;
String title = "Dart";
String? bio;
Object box = title;

Null helpers

String label = bio ?? "guest";
int? len = bio?.length;
bio ??= "guest";
String sure = bio!;

Null forms

FormMeaning
StringNever null
String?String or null
??Use the right side when the left is null
?.Call only when the receiver is not null
!Assert non-null. Throws if you are wrong
latePromise to assign before the first read

Operators & Cascades

Checks

if (value is String) {
  print(value.length);
}
if (value is! int) {
  print("not an int");
}

Cascade writes the same object

final buffer = StringBuffer()
  ..write("Hello")
  ..write(" Dart");
print(buffer.toString());

Which dot

OpReturns
.The method result. Chaining uses this
..The receiver. Use it to configure one object
?..Cascade only when the receiver is not null
??First non-null value
=>Expression body. One expression, no block

Control Flow & Patterns

if and for

String grade;
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "C";
}

for (final tag in tags) {
  print(tag);
}

Switch expression

final label = switch (status) {
  Status.draft => "Draft",
  Status.live => "Live",
};

Patterns

FormUse
if (value is String s)Test and bind in one step
switch on an enum or sealed typeMust be exhaustive. A missing case is an error
case Status.draft:Statement form. Still no fall-through
when score > 90Extra guard on a case

Dart 3 switch statements do not fall through. You do not write break after every case.

Functions

Named and positional

String greet(String name, {String title = "Hi"}) {
  return "$title, $name";
}

int add(int a, int b) => a + b;

void log(String message, [String? tag]) {
  print(tag ?? message);
}

Required named argument

User create({required String name, int age = 0}) {
  return User(name, age: age);
}

final user = create(name: "Ravi");

Argument forms

FormCall site
String namePositional and required: greet("Ravi")
{String title = "Hi"}Named and optional: greet("Ravi", title: "Hello")
{required String name}Named and required. The caller must pass name:
[String? tag]Optional positional. Wrap in square brackets
=> exprOne expression. No return keyword

Lists, Sets & Maps

Create and update

final tags = <String>["dart", "flutter"];
tags.add("web");

final user = <String, String>{
  "name": "Ravi",
  "city": "Hyderabad",
};
print(user["name"]);

Transform

final doubled = nums.map((n) => n * 2).toList();
final adults = users.where((u) => u.age >= 18).toList();
final names = users.map((u) => u.name).toSet();

Which collection

TypeWhen
List<T>Ordered. Index with []. Default choice
Set<T>Unique items. Fast contains
Map<K, V>Lookup by key. Missing key reads as null
...listSpread into another collection
...?listSpread only when the list is not null
if (ok) itemInclude an element only when the condition is true

list1 == list2 compares identity, not contents. Two lists with the same items are not equal unless you compare them yourself.

Classes, Mixins & Enums

Initializing formals

class User {
  User(this.name, {required this.age});

  final String name;
  final int age;

  String greet() => "Hi, $name";
}

Mixin and enum

mixin Id {
  String id = "x";
}

class Post with Id {
  Post(this.title);
  final String title;
}

enum Status { draft, live }

Reuse

KeywordRule
extendsOne superclass
implementsAny number of interfaces. You write every member
withMix in reusable members. No constructor of their own
abstractCannot be constructed. Subclasses fill in the gaps
sealedSubclasses live in the same library. Switches must be exhaustive
enumA fixed set of values. Enhanced enums can have fields

Records & Sealed Types

A record

(int, String) pair = (21, "Ravi");
final point = (x: 1, y: 2);
print(point.x);

Sealed hierarchy

sealed class Shape {}

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

class Rect extends Shape {
  Rect(this.width, this.height);
  final double width;
  final double height;
}

Records are values. Two records with the same fields are equal. A sealed class is the Dart way to get an exhaustive switch: add a subclass and the compiler shows every switch you forgot.

Futures & async

await a Future

Future<String> load() async {
  return "ok";
}

Future<void> run() async {
  final text = await load();
  print(text);
}

Handle failure

try {
  final text = await load();
  print(text);
} catch (error, stack) {
  print(error);
} finally {
  print("done");
}

Async types

TypeMeaning
Future<T>One value, later
Future<void>Work with no useful result
Stream<T>Many values over time. await for reads them
asyncThe function returns a Future
awaitPause this function until the Future completes. Does not block the isolate

Forgetting await starts the work and drops the result and the error. An unawaited Future that throws becomes an unhandled async error.

Interview Traps

Traps worth memorising

TrapWhat happensPrefer
dynamicNo member checksA real type, or Object plus is
name! when it might be nullThrows at runtime?? or an if (name != null)
late read before assignThrows LateInitializationErrorAssign on the line you declare it, when you can
== on two listsIdentity, not contentsCompare with a loop, or listEquals from package:flutter/foundation.dart
. when you wanted ..You get the method result, often voidCascade when you mean “keep this object”
const on a runtime valueCompile errorfinal for one assignment at runtime
Missing awaitErrors disappear. The UI moves onAwait it, or return the Future
await inside a loopRequests run one after anotherFine when order matters. Otherwise start them, then await
Switch missing a sealed subtypeCompile errorHandle the new subtype. That is the feature
String.length for Hindi or emojiCounts UTF-16 code units, not graphemesThe characters package when the user sees the text
Mutable final listfinal blocks reassignment, not addA const list, or stop mutating it
print in production FlutterNoisy logsdebugPrint, or a logger

final is not deep

final tags = <String>["dart"];
tags.add("flutter");
tags = <String>[];

Check, then use

void show(String? name) {
  if (name == null) return;
  print(name.length);
}

How to use this page: the last line of the final sample does not compile. That is the point. Type a sealed class with two subclasses and a switch, then add a third subclass and let the analyzer find the missing case.