Dart Cheat Sheet

By Syncfusion®, Inc. · Last updated

A lookup page for the whole course: one table per topic, from data types and null safety to classes, patterns, async code, files and JSON.

What Is This Page?

Reference page = a page you look things up in, not one you read from top to bottom.

Nobody remembers every method name. Programmers remember that a tool exists, then look up how to spell it.

This page gives you:

  • one table per topic, in course order
  • a Run box wherever seeing beats reading
  • the traps worth keeping in your head

Simple lesson: remember that a tool exists, and look up the details here.

A Real-World Example

A developer building a school app forgets whether it is trim() or strip(). They do not reread a whole tutorial. They open a reference, find the strings table, and get the answer in seconds. This page is that reference for everything in the course.

types and null safety

if, switch, loops

functions, libraries

lists, sets, maps

classes and patterns

async, files, JSON

Dart

Every topic of the course, on one page.

Here is most of the course working together in one program:

The whole course in one program

class Result {
  final String name;
  final String subject;
  final int mark;

  Result(this.name, this.subject, this.mark);

  String get grade => mark >= 35 ? 'pass' : 'fail';
}

void main() {
  var results = [
    Result('Asha', 'Maths', 78),
    Result('Ravi', 'Science', 85),
    Result('Meera', 'English', 30),
  ];

  results.sort((a, b) => b.mark.compareTo(a.mark));
  for (var r in results) {
    print('${r.name.padRight(8)}${r.subject.padRight(10)}${r.mark.toString().padLeft(4)}  ${r.grade}');
  }

  var passed = results.where((r) => r.grade == 'pass').length;
  var average = results.map((r) => r.mark).reduce((a, b) => a + b) / results.length;
  print('$passed of ${results.length} passed, average ${average.toStringAsFixed(1)}');
}

Open this page at the section you need. Each heading matches a lesson you can go back to.

What You Will Learn

On this page, you will find:

  1. The syntax for every topic in the course.
  2. Run boxes for the trickiest parts.
  3. The traps worth remembering, in one table.

Data Types

Every basic type from the course, side by side:

TypeExampleNotes
int78Whole numbers
double78.5Not exact: 0.1 + 0.2 != 0.3
num78 or 78.5Either int or double
String'Asha'Cannot change. Every method returns a new string
booltrueOnly true and false. if (1) does not compile
List<int>[78, 85]Ordered, duplicates allowed
Set<int>{78, 85}No duplicates
Map<String, int>{'Asha': 78}Keys are unique
int?nullThe ? allows null
dynamicanythingNo type checks. Avoid it

The ways to make a variable:

FormExampleCan change?
varvar marks = 78;Yes. Type fixed from the value
Type nameint marks = 78;Yes
finalfinal name = 'Asha';No. Set once, at run time
constconst passMark = 35;No. Known before the program runs
latelate String title;Set later, before first use

Checking and converting

void main() {
  var text = '78';
  print(text.runtimeType);
  print(int.parse(text) + 2);
  print(int.tryParse('abc'));
  print(double.parse('78.5').round());
  print(78.toString().length);
  print((2 / 3).toStringAsFixed(2));
}

int.parse crashes on bad text. int.tryParse gives null instead.

Keywords

Keyword = a word Dart keeps for itself. You cannot use most of them as names.

GroupKeywords
Variablesvar final const late
Decideif else switch case default when
Repeatfor in while do break continue
Functionsreturn void async await yield sync
Classesclass extends implements with mixin abstract enum extension
Modifierssealed base interface final static factory covariant
Errorstry catch on finally throw rethrow
Librariesimport export library part show hide as deferred

Contextual keyword = a word like on, show or async that is special only in one place. You can still use it as a variable name.

Operators

The operator groups:

GroupOperators
Arithmetic+ - * / ~/ %
Increase / decrease++ --
Comparison== != > < >= <=
Assignment= += -= *= /= ~/= ??=
Logical&& || !
Type testis is! as
Null-aware?. ?? ??= ! ?[]
Choosecond ? a : b
Cascade.. ?..
Spread... ...?

The ones that surprise people

void main() {
  print(7 / 2);
  print(7 ~/ 2);
  print(-7 ~/ 2);
  print(7 % 2);
  int? bonus;
  print(88 + (bonus ?? 5));
  var list = [3, 1, 2]..sort();
  print(list);
}

/ always gives a double. ~/ gives an int and drops the part after the point.

Null Safety

SyntaxMeaningExample
T?This variable may be nullString? name;
a ?? bb if a is nullname ?? 'Guest'
a ??= bSet a only if it is nullname ??= 'Guest';
a?.bUse b only if a is not nullname?.length
a!"I promise this is not null"name!.length
lateWill be set before first uselate final int id;

! does not fix a null. It only moves the crash to run time. Check for null first, or use ??.

Conditional Statements

FormSyntaxNotes
if / elseif (a) {} else if (b) {} else {}Brackets around the condition
Ternaryvar r = m >= 35 ? 'pass' : 'fail';A short if that gives a value
switch statementswitch (v) { case 1: ...; default: ... }No break needed
switch expressionvar x = switch (v) { 1 => 'a', _ => 'b' };_ matches anything else
Guardcase int m when m >= 90:An extra check on a case

Loops

LoopSyntaxUse it when
Counting forfor (var i = 0; i < n; i++) { }You need the position
for-infor (var x in xs) { }You need every item
forEachxs.forEach((x) => print(x));A short action per item
whilewhile (x < 100) { }You do not know how many times
do-whiledo { } while (x < 100);It must run at least once
Controlbreak, continue, outer: for ... then break outer;Leave or skip

Functions

TopicSyntaxNotes
Declareint add(int a, int b) { return a + b; }Return type first
Arrowint add(int a, int b) => a + b;For one expression
Optionalvoid greet(String n, [String? title])Square brackets
Namedvoid greet({required String name, int age = 0})Called with greet(name: 'Asha')
Anonymous(x) => x * 2A function with no name
Closurevar add5 = makeAdder(5);Remembers values from where it was made
Function typeint Function(int) fA function as a value

Control flow and functions

String grade(int m) => switch (m) {
  >= 90 => 'A',
  >= 75 => 'B',
  _ => 'C',
};

void greet({required String name, String title = 'Student'}) {
  print('Hello, $title $name');
}

void main() {
  for (var m in [95, 80, 60]) {
    print('$m: ${grade(m)}');
  }
  greet(name: 'Asha');
}

Libraries and Packages

TaskSyntax
Core libraryimport 'dart:math';
Packageimport 'package:http/http.dart' as http;
Your own fileimport 'marks.dart';
Only some namesimport 'dart:math' show max, min;
All but someimport 'dart:math' hide Random;
Add a packagedart pub add http
Private nameStart it with _: _total

The core libraries you will use most: dart:core (automatic), dart:math, dart:convert, dart:io, dart:async, dart:isolate.

Collections

CollectionMakeAdd / changeNotes
List[1, 2], List.filled(3, 0)add, insert, removeAt, sortIndex from 0 to length - 1
Set{1, 2}, <int>{}add, remove, union, intersection{} alone is an empty Map
Map{'a': 1}, <String, int>{}m['b'] = 2, remove, putIfAbsentm['x'] is null when missing
Spread[...a, ...b]—Joins collections
Collection if / for[if (ok) 'a', for (var x in xs) x * 2]—Build lists with logic

The iterable methods:

MethodGivesExample
mapEach item changedxs.map((x) => x * 2)
whereItems that passxs.where((x) => x >= 80)
fold / reduceOne valuexs.fold(0, (a, b) => a + b)
any / everytrue or falsexs.any((x) => x < 35)
firstWhereFirst matchxs.firstWhere((x) => x > 90, orElse: () => 0)
toList() / toSet()A real collectionxs.map(...).toList()

Collections in one go

void main() {
  var marks = {'Asha': 92, 'Ravi': 75, 'Priya': 85};
  var good = marks.entries.where((e) => e.value >= 80).map((e) => e.key).toList();
  print(good);
  print(marks.values.fold(0, (a, b) => a + b));
  var unique = {...[1, 2, 2, 3]};
  print(unique);
}

String Methods

MethodExampleResult
length'Asha'.length4
toUpperCase / toLowerCase'asha'.toUpperCase()'ASHA'
trim' hi '.trim()'hi'
contains'Green Valley'.contains('Val')true
startsWith / endsWith'a.txt'.endsWith('.txt')true
indexOf'Asha'.indexOf('h')2
substring'Valley'.substring(0, 3)'Val'
split / join'a,b'.split(',')['a', 'b']
replaceAll'8-A'.replaceAll('-', '')'8A'
padLeft / padRight'7'.padLeft(3, '0')'007'

Also remember:

  • '$name' puts a variable in text. '${a + b}' puts an expression.
  • '''...''' makes text over many lines.
  • For many joins, use StringBuffer: sb.write('x'), then sb.toString().

Date and Time

TaskSyntaxNotes
NowDateTime.now()
Make oneDateTime(2026, 11, 14, 9, 30)Months start at 1
ParseDateTime.parse('2026-11-14')ISO format
DurationDuration(days: 1, hours: 3)
Add / subtractd.add(Duration(days: 2)), d2.difference(d1)difference gives a Duration
Compared1.isBefore(d2), d1.isAfter(d2)
Partsd.year, d.month, d.day, d.weekdayweekday: Monday is 1

Strings and dates

void main() {
  var parts = 'Asha,8A,91'.split(',');
  print('${parts[0].toUpperCase()} ${parts.length}');
  var exam = DateTime(2026, 11, 14, 9, 30);
  var end = exam.add(Duration(hours: 3));
  print('${end.hour}:${end.minute.toString().padLeft(2, '0')}');
  print(DateTime(2026, 12, 25).difference(exam).inDays);
}

Classes and Objects

TopicSyntaxNotes
Classclass Student { String name; int marks; ... }A blueprint
ConstructorStudent(this.name, this.marks);this. fills fields
Named constructorStudent.guest() : name = 'Guest', marks = 0;Another way to make one
Factoryfactory Student.fromJson(Map m) => ...Can return a checked or existing object
Private fieldint _marks;Private to the file
Getter / setterint get marks => _marks; set marks(int v) {...}Controlled access
Staticstatic int count = 0;Belongs to the class, not each object
CascadeStudent('Asha', 0)..marks = 90Many calls on one object

Inheritance, Polymorphism and Mixins

KeywordMeansExample
extends"is a", gets the parent's codeclass Teacher extends Person
@overrideReplaces a parent method@override String toString()
superThe parent's versionsuper.greet(), Teacher(super.name)
abstractCannot be made, only extendedabstract class Shape { double area(); }
implementsPromises the same methodsclass Dog implements Pet
withAdds a mixin's methodsclass Robot with Walker
mixinReusable methods without a parentmixin Walker { void walk() {} }
extensionAdds methods to an existing typeextension on String { ... }
call()Makes an object usable like a functionadder(5)

The class modifiers:

ModifierOutside the library, others can...
(none)extend and implement
baseextend only
interfaceimplement only
finalneither
sealedneither, and switch knows every subtype
abstractextend and implement, but not make one

A small class family

abstract class Shape {
  double area();
}

class Square extends Shape {
  final double side;
  Square(this.side);
  @override
  double area() => side * side;
}

mixin Named {
  String get label => 'Shape #1';
}

class LabelledSquare extends Square with Named {
  LabelledSquare(super.side);
}

void main() {
  var s = LabelledSquare(2.5);
  print('${s.label}: ${s.area()}');
}

Enums and Generics

TopicSyntaxNotes
Simple enumenum House { red, blue, green }House.red.name is 'red'
Enhanced enumenum Grade { a(90), b(75); final int min; const Grade(this.min); }Fields and methods
All valuesHouse.valuesA list
Generic classclass Box<T> { T value; Box(this.value); }T is filled in later
Generic functionT first<T>(List<T> xs) => xs[0];
Limit the type<T extends num>Only numbers allowed

Records and Patterns

TopicSyntaxNotes
Recordvar r = ('Asha', age: 13);r.$1, r.age
Return two values(int, int) minMax(...)No class needed
Destructurevar (a, b) = pair;
List patternvar [first, ...rest] = list;
Map patternif (json case {'name': String n}) {...}Checks shape and type
Object patterncase Student(:name, :marks):Pulls fields out
Guardcase (var x, _) when x > 0:Extra check

Records and patterns

(int, int) minMax(List<int> xs) {
  var sorted = [...xs]..sort();
  return (sorted.first, sorted.last);
}

void main() {
  var (low, high) = minMax([72, 95, 64]);
  print('$low to $high');
  var data = {'name': 'Ravi', 'marks': 75};
  if (data case {'name': String n, 'marks': int m} when m >= 35) {
    print('$n passed');
  }
}

Exception Handling

PartSyntaxNotes
Trytry { ... }Code that may fail
Catch a typeon FormatException { ... }Specific first
Catch and seecatch (e, s) { ... }e = error, s = stack trace
Always runfinally { ... }Runs on both paths
Throwthrow FormatException('bad marks');
Throw againrethrow;Inside a catch
Your ownclass MarksException implements Exception { ... }

Exception = something that can go wrong in normal use, like bad input. Error = a bug in the program, like a wrong index. Catch exceptions, fix errors.

Async: Futures, Streams and Isolates

PieceSyntaxFor
FutureFuture<int> load() async { ... }One value, later
Waitvar x = await load();Only inside async
Many at onceawait Future.wait([a(), b()])Run together, wait for all
Time limitawait load().timeout(Duration(seconds: 2))
StreamStream<int> count() async* { yield 1; }Many values, over time
Read a streamawait for (var x in s) { }, s.listen(...)
ControllerStreamController<int>()Make your own stream
Isolateawait Isolate.run(() => heavyWork())Heavy maths without freezing

File Handling and JSON

TaskSyntaxNotes
Read allFile('a.txt').readAsStringSync()Or await readAsString()
Read linesFile('a.txt').readAsLinesSync()A list of lines
WriteFile('a.txt').writeAsStringSync(text)Replaces the file
AppendwriteAsStringSync(t, mode: FileMode.append)Adds to the end
Exists?File('a.txt').existsSync()
FolderDirectory('reports').createSync(recursive: true)
To JSONjsonEncode(map)Needs import 'dart:convert';
From JSONjsonDecode(text)Gives Map or List
In a classtoJson() and factory X.fromJson(Map m)

Async, exceptions and JSON together

import 'dart:convert';

Future<String> fetch() => Future.delayed(Duration(seconds: 1), () => '{"name": "Asha", "marks": [92, 88]}');

Future<void> main() async {
  try {
    var data = jsonDecode(await fetch());
    print('${data['name']}: ${data['marks']}');
    jsonDecode('oops');
  } on FormatException {
    print('Bad JSON skipped');
  } finally {
    print('done');
  }
}

Forgot a method? Ask your editor. Type a dot after a value, like name., and it lists everything that value can do. Hover over a method to read what it does.

Easy Way to Remember:

  • Forgot a name? Type . and let the editor list it.
  • Not sure of the type? Print x.runtimeType.
  • Got an error? Read the first line: file, line number, then the problem.

TL;DR

  1. Types = int, double, String, bool, List, Set, Map, and ? for null.
  2. Variables = var, final, const, late.
  3. Control flow = if, switch expressions, for, for-in, while.
  4. Functions = arrow =>, optional [], named {}, closures.
  5. OOP = classes, extends, implements, with, modifiers, generics, enums.
  6. Records and patterns = (a, b), var (x, y) =, case, when.
  7. Safety = try / on / catch / finally.
  8. Async and data = async / await, Streams, isolates, dart:io, dart:convert.

Common mistakes

The most common mistakes from the whole course, in one place.

MistakeWhat you seeWhy it happensFix
7 / 2 expected to be 33.5/ always gives a double7 ~/ 2
= in a conditionA compile error= sets, == comparesif (a == b)
Using ! on a null valueNull check operator used on a null value! only promisesCheck first, or use ??
Forgetting awaitInstance of 'Future<String>'The call gives a Futureawait load()
list[list.length]RangeErrorThe last index is length - 1list.last
{} meant as an empty setIt is a Map{} means an empty map<int>{}
int.parse('abc')FormatExceptionThe text is not a numberint.tryParse and ??
A missing importUndefined name 'jsonEncode'Not in dart:coreimport 'dart:convert';
DateTime(2026, 0, 1)December of the year beforeMonths start at 1Use 1 for January
catch (e) above on FormatExceptionThe specific block never runsFirst match winsSpecific first
Writing a file without FileMode.appendOld text is goneWrite replacesmode: FileMode.append
Setting a final variable againA compile errorfinal locks the variableChange the items, or use var

Check Yourself

Exercises

What to Remember

  • Nobody remembers everything. Know a tool exists, and look up the spelling.
  • Type . after a value and your editor lists what it can do.
  • / gives a double. ~/ gives an int.
  • T? allows null. Handle it with ??, ?. or a check, not with !.
  • final is set once at run time. const is fixed before the program runs.
  • {} is an empty map. Write <int>{} for an empty set.
  • Months in DateTime start at 1.
  • async functions give a Future. await it before you use the value.
  • The first matching on block wins, so go specific to general.
  • Writing a file replaces it. Use FileMode.append to add.

You have finished the Dart course. Next, try building a small app of your own, like a marks tracker that saves to a JSON file.