Comprehensive Dart cheatsheet with TOC covering syntax, variables, operators, control flow, functions, collections, OOP, null safety, async/await, streams, exceptions, libraries, and Dart 3 features (records, patterns). Perfect quick reference for beginners and pros.
- Basics
- Variables & Data Types
- Operators
- Control Flow
- Functions
- Collections
- Object-Oriented Programming (OOP)
- Exception Handling
- Asynchronous Programming
- Libraries & Imports
- Null Safety
- Common Useful Features
void main() {
print('Hello, Dart!');
}main()is the required entry point.- Use
void main(List<String> args)to accept command-line arguments.
// Single-line comment
/*
Multi-line comment
*/
/// Documentation comment (for dartdoc)var name = 'Alice'; // Type inferred
String name = 'Alice'; // Explicit type
dynamic anything = 42; // Can change type
Object something = 'hi'; // Base classlate String description; // Initialized later
description = 'now set';const pi = 3.14; // Compile-time constant
final answer = 42; // Run-time constant (set once)| Type | Example |
|---|---|
int |
int age = 30; |
double |
double price = 9.99; |
num (int/double) |
num x = 10; x = 10.5; |
String |
String name = 'Dart'; |
bool |
bool isReady = true; |
List |
List<int> nums = [1, 2, 3]; |
Set |
Set<String> names = {'a', 'b'}; |
Map |
Map<String, int> ages = {'Bob': 25}; |
Runes |
Unicode code points |
Symbols |
#mySymbol (rare) |
int age = 25;
print('I am $age years old'); // I am 25 years old
print('Next year: ${age + 1}'); // Next year: 26+ - * / // Basic
~/ // Integer division
% // Modulus
++ -- // Increment/decrement== != > < >= <=
&& || ! // AND, OR, NOTis // True if object has type
is! // True if object does NOT have type
as // Type cast??= // Assign if null
?? // If null, use alternative
?. // Safe navigation
... // Spread operatorExample:
int? a;
int b = a ?? 10; // b = 10
a ??= 5; // a = 5
print(a?.isEven); // Safe accessif (condition) {
// ...
} else if (other) {
// ...
} else {
// ...
}switch (value) {
case 1:
print('one');
break;
case 2:
print('two');
break;
default:
print('other');
}
// Dart 3.0: Switch expressions
var result = switch (value) { 1 => 'one', 2 => 'two', _ => 'other' };// For loop
for (int i = 0; i < 5; i++) { print(i); }
// For-in
var list = [1, 2, 3];
for (var item in list) { print(item); }
// ForEach (functional)
list.forEach((item) => print(item));
// While / Do-while
while (condition) { }
do { } while (condition);break; // Exit loop/switch
continue; // Skip to next iterationint add(int a, int b) {
return a + b;
}int add(int a, int b) => a + b;// Positional optional (must be in order, default null or value)
void greet(String name, [String? title]) {
print('$title $name');
}
greet('Alice', 'Ms.');
// Named parameters (with defaults or required)
void register({required String name, int age = 0}) {
print('$name, $age');
}
register(name: 'Bob', age: 25);var square = (int x) => x * x;
print(square(5)); // 25void doSomething(void Function() callback) {
callback();
}Function makeCounter() {
int count = 0;
return () => count++;
}var list = [1, 2, 3];
list.add(4); // [1,2,3,4]
list.removeAt(0); // [2,3,4]
list[1] = 99; // [2,99,4]
print(list.length); // 3
// List literals with spread/collection if
var other = [0, ...list];
var withIf = [1, if (condition) 2];
var withFor = [for (var i in list) i * 2];var set = {1, 2, 3};
set.add(2); // No duplicate
set.add(4);
print(set.contains(3)); // truevar map = {'a': 1, 'b': 2};
map['c'] = 3;
print(map['a']); // 1
map.forEach((k, v) => print('$k: $v'));var nums = [1, 2, 3, 4];
var evens = nums.where((n) => n % 2 == 0); // (2,4)
var squares = nums.map((n) => n * n); // (1,4,9,16)
var sum = nums.reduce((a, b) => a + b); // 10
var hasBig = nums.any((n) => n > 3); // trueclass Person {
String name;
int age;
// Constructor
Person(this.name, this.age);
// Named constructor
Person.guest() : name = 'Guest', age = 0;
// Method
void greet() => print('Hi, I am $name');
// Getter/Setter
String get display => '$name ($age)';
set setAge(int a) => age = a;
}class Student extends Person {
int grade;
Student(String name, int age, this.grade) : super(name, age);
@override
void greet() => print('I am a student');
}abstract class Animal {
void makeSound(); // Abstract method
}
class Dog implements Animal {
@override
void makeSound() => print('Woof');
}mixin Flyable {
void fly() => print('Flying');
}
class Bird with Flyable {}class MathUtil {
static const pi = 3.14;
static int add(int a, int b) => a + b;
}
print(MathUtil.pi);try {
int result = 100 ~/ 0;
} catch (e, stackTrace) {
print('Error: $e');
print(stackTrace);
} finally {
print('Always runs');
}try {
// ...
} on IntegerDivisionByZeroException {
print('Cannot divide by zero');
} catch (e) {
print('Other error: $e');
}void validateAge(int age) {
if (age < 0) throw Exception('Age cannot be negative');
}Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
void main() async {
print('Loading...');
String data = await fetchData();
print(data);
}try {
var result = await riskyOperation();
} catch (e) {
print('Failed: $e');
}fetchData().then((value) {
print(value);
}).catchError((error) {
print(error);
});Stream<int> countStream(int max) async* {
for (int i = 1; i <= max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() async {
await for (var value in countStream(3)) {
print(value);
}
}import 'dart:io'; // Core library
import 'package:http/http.dart' as http; // Package with alias
import 'my_file.dart'; // Local file// In library.dart
export 'src/helper.dart' show usefulFunction;// In main_lib.dart
part 'helper.dart';
// In helper.dart
part of 'main_lib.dart';- Types are non-nullable by default.
- Add
?to make nullable.
String? nullableString = null;
int? nullableInt;String? maybeName = getUserName();
int length = maybeName!.length; // Assumes not null — dangerous if nulllate String description; // No initial value, but non-nullable
description = 'ready'; // Must set before usevoid myFunction({required int value}) { }void printLength(String? str) {
if (str != null) {
print(str.length); // str promoted to non-nullable String
}
}typedef IntCallback = int Function(int a, int b);
int add(int a, int b) => a + b;
IntCallback calc = add;enum Status { pending, success, failed }
// With values/methods
enum Color {
red('#FF0000'),
green('#00FF00');
final String hexCode;
const Color(this.hexCode);
}extension NumberParsing on String {
int toInt() => int.parse(this);
}
print('123'.toInt()); // 123var record = (name: 'Alice', age: 25);
print(record.name); // Alice
print(record.$1); // Alice (positional access)var (a, b) = (1, 2);
switch (obj) {
case [var first, var second]: print('$first, $second');
case int x when x > 0: print('Positive $x');
}var list = [1, 2, 3]
..add(4)
..removeAt(0);assert(condition, 'Optional error message');
// Only checks in development mode| Task | Code |
|---|---|
print('text'); |
|
| Null-safe access | obj?.property |
| List literal | [1, 2, 3] |
| Map literal | {'a': 1} |
| Async loop | await for (var x in stream) |
| Future delay | await Future.delayed(Duration(seconds: 1)); |
| Spread | [...list] |
| Collection if/for | [if(cond) 1, for(x in list) x] |
| Class constructor | ClassName(this.prop1, this.prop2); |