Skip to content

cheatnotes/dart-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Dart Programming Cheatsheet

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.

Table of Contents

  1. Basics
  2. Variables & Data Types
  3. Operators
  4. Control Flow
  5. Functions
  6. Collections
  7. Object-Oriented Programming (OOP)
  8. Exception Handling
  9. Asynchronous Programming
  10. Libraries & Imports
  11. Null Safety
  12. Common Useful Features

1. Basics

Hello World

void main() {
  print('Hello, Dart!');
}

Entry Point

  • main() is the required entry point.
  • Use void main(List<String> args) to accept command-line arguments.

Comments

// Single-line comment

/*
  Multi-line comment
*/

/// Documentation comment (for dartdoc)

2. Variables & Data Types

Variable Declaration

var name = 'Alice';          // Type inferred
String name = 'Alice';       // Explicit type
dynamic anything = 42;       // Can change type
Object something = 'hi';     // Base class

Late Initialization

late String description;   // Initialized later
description = 'now set';

Constants

const pi = 3.14;           // Compile-time constant
final answer = 42;         // Run-time constant (set once)

Built-in Types

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)

String Interpolation

int age = 25;
print('I am $age years old');     // I am 25 years old
print('Next year: ${age + 1}');    // Next year: 26

3. Operators

Arithmetic

+   -   *   /       // Basic
~/          // Integer division
%           // Modulus
++   --     // Increment/decrement

Comparison & Logical

==   !=   >   <   >=   <=
&&   ||   !             // AND, OR, NOT

Type Test

is    // True if object has type
is!   // True if object does NOT have type
as    // Type cast

Assignment & Null-aware

??=       // Assign if null
??        // If null, use alternative
?.        // Safe navigation
...       // Spread operator

Example:

int? a;
int b = a ?? 10;       // b = 10
a ??= 5;               // a = 5
print(a?.isEven);      // Safe access

4. Control Flow

If-Else

if (condition) {
  // ...
} else if (other) {
  // ...
} else {
  // ...
}

Switch

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' };

Loops

// 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 & Continue

break;    // Exit loop/switch
continue; // Skip to next iteration

5. Functions

Basic Function

int add(int a, int b) {
  return a + b;
}

One-line (fat arrow)

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

Optional Parameters

// 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);

Anonymous Function (Lambda)

var square = (int x) => x * x;
print(square(5)); // 25

Functions as First-class Objects

void doSomething(void Function() callback) {
  callback();
}

Lexical Closures

Function makeCounter() {
  int count = 0;
  return () => count++;
}

6. Collections

List (Array)

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];

Set (Unique items)

var set = {1, 2, 3};
set.add(2);          // No duplicate
set.add(4);
print(set.contains(3)); // true

Map (Key-Value)

var map = {'a': 1, 'b': 2};
map['c'] = 3;
print(map['a']);     // 1
map.forEach((k, v) => print('$k: $v'));

Collection Methods (Where, Map, Reduce)

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);          // true

7. Object-Oriented Programming (OOP)

Class Definition

class 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;
}

Inheritance

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 & Interface

abstract class Animal {
  void makeSound();  // Abstract method
}

class Dog implements Animal {
  @override
  void makeSound() => print('Woof');
}

Mixins

mixin Flyable {
  void fly() => print('Flying');
}

class Bird with Flyable {}

Static Members

class MathUtil {
  static const pi = 3.14;
  static int add(int a, int b) => a + b;
}
print(MathUtil.pi);

8. Exception Handling

Try-Catch-Finally

try {
  int result = 100 ~/ 0;
} catch (e, stackTrace) {
  print('Error: $e');
  print(stackTrace);
} finally {
  print('Always runs');
}

Specific Catch

try {
  // ...
} on IntegerDivisionByZeroException {
  print('Cannot divide by zero');
} catch (e) {
  print('Other error: $e');
}

Throw

void validateAge(int age) {
  if (age < 0) throw Exception('Age cannot be negative');
}

9. Asynchronous Programming

Future & async/await

Future<String> fetchData() async {
  await Future.delayed(Duration(seconds: 2));
  return 'Data loaded';
}

void main() async {
  print('Loading...');
  String data = await fetchData();
  print(data);
}

Handle Errors with async/await

try {
  var result = await riskyOperation();
} catch (e) {
  print('Failed: $e');
}

Future API (then, catchError)

fetchData().then((value) {
  print(value);
}).catchError((error) {
  print(error);
});

Streams

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);
  }
}

10. Libraries & Imports

Import

import 'dart:io';          // Core library
import 'package:http/http.dart' as http;  // Package with alias
import 'my_file.dart';      // Local file

Export parts of library

// In library.dart
export 'src/helper.dart' show usefulFunction;

Part / Part of (splitting large libraries)

// In main_lib.dart
part 'helper.dart';

// In helper.dart
part of 'main_lib.dart';

11. Null Safety

Introduction (Dart 2.12+)

  • Types are non-nullable by default.
  • Add ? to make nullable.

Nullable Types

String? nullableString = null;
int? nullableInt;

Null Assertion Operator (!)

String? maybeName = getUserName();
int length = maybeName!.length; // Assumes not null — dangerous if null

Late Variables

late String description;  // No initial value, but non-nullable
description = 'ready';    // Must set before use

Required Named Parameters

void myFunction({required int value}) { }

Type Promotion

void printLength(String? str) {
  if (str != null) {
    print(str.length);   // str promoted to non-nullable String
  }
}

12. Common Useful Features

Typedef (type alias)

typedef IntCallback = int Function(int a, int b);
int add(int a, int b) => a + b;
IntCallback calc = add;

Enums (enhanced in Dart 3)

enum Status { pending, success, failed }

// With values/methods
enum Color {
  red('#FF0000'),
  green('#00FF00');
  final String hexCode;
  const Color(this.hexCode);
}

Extension Methods

extension NumberParsing on String {
  int toInt() => int.parse(this);
}
print('123'.toInt());  // 123

Records (Dart 3+)

var record = (name: 'Alice', age: 25);
print(record.name);  // Alice
print(record.$1);    // Alice (positional access)

Patterns (Dart 3+)

var (a, b) = (1, 2);
switch (obj) {
  case [var first, var second]: print('$first, $second');
  case int x when x > 0: print('Positive $x');
}

Cascade Notation (..)

var list = [1, 2, 3]
  ..add(4)
  ..removeAt(0);

Assert

assert(condition, 'Optional error message');
// Only checks in development mode

Quick Reference Card

Task Code
Print 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);

About

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.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Generated from cheatnotes/cheatnotes