All Cheatsheets

Dart

Dart

Dart is an open-source, general-purpose programming language created by Google in 2011. It is object-oriented, class-based, and type-safe, with a C-style syntax that is easy to pick up. Dart is best known as the language behind Flutter, but it also runs on servers, the command line, and the web.

Key Features -
  • Type-Safe : Statically typed with sound null safety, catching many errors before the program runs, while still allowing type inference with var.
  • Object-Oriented : Everything is an object, even numbers and functions; every object is an instance of a class.
  • Compiles Two Ways : JIT (Just-In-Time) compilation gives fast hot reload during development; AOT (Ahead-Of-Time) compiles to fast native machine code for release.
  • Cross-Platform : Runs on mobile, web, desktop, and servers from one codebase.
  • Async Built-In : First-class support for asynchronous programming with Futures, Streams, and async / await.
// every Dart program starts at main() void main() { print('Hello, Dart!'); }

Setup & Commands

The Dart SDK provides the dart command-line tool for running, compiling, and managing projects. It comes bundled with Flutter, or can be installed on its own.

dart --version # check installed version dart create my_app # create a new project dart run # run the project dart run bin/main.dart # run a specific file dart compile exe main.dart # compile to native executable dart analyze # check code for errors and warnings dart format . # auto-format all files dart test # run tests
Packages (pub) -

Dart uses pub as its package manager, with dependencies listed in pubspec.yaml and packages hosted on pub.dev.

dart pub get # install dependencies from pubspec.yaml dart pub add http # add a package dart pub upgrade # update packages

Variables & Types

Declare variables with an explicit type, or use var to let Dart infer it. Use final and const for values that never change.

var name = 'Ada'; // inferred as String String city = 'London'; // explicit type final age = 36; // set once at runtime, cannot reassign const pi = 3.14; // compile-time constant dynamic anything = 5; // type can change (avoid when possible)
Built-in Types -
  • int : Whole numbers, e.g. 42.
  • double : Floating-point numbers, e.g. 3.14. Both int and double are subtypes of num.
  • String : Text in single or double quotes; supports interpolation with $.
  • bool : true or false.
  • List : An ordered collection (array).
  • Map : Key-value pairs.
  • Set : An unordered collection of unique values.
String Interpolation -
var name = 'Ada'; print('Hello, $name'); // simple variable print('Name has ${name.length} letters'); // expression in ${}
  • final vs const : final is set once when the code runs; const must be known at compile time and is a fixed constant.

Operators

  • Arithmetic : +, -, *, / (double result), ~/ (integer division), % (remainder).
  • Comparison : ==, !=, >, <, >=, <=.
  • Logical : && (and), || (or), ! (not).
  • Assignment : =, +=, -=, and ??= (assign only if currently null).
Null-Aware Operators -
  • ?. : Call a member only if the object is not null: user?.name.
  • ?? : Provide a fallback when a value is null: name ?? 'Guest'.
  • ! : Assert a value is not null (use carefully): value!.
int? a; // nullable, currently null int b = a ?? 0; // b = 0 because a is null a ??= 10; // a becomes 10 (was null) print(a?.isEven); // safe call, prints true

Null Safety

Dart has sound null safety: variables cannot hold null unless you explicitly allow it with a ?. This eliminates a whole class of "null reference" crashes by catching them at compile time.

  • Non-Nullable (default) : String name can never be null and must be initialized.
  • Nullable : String? name may hold a value or null.
  • late : Promises to set a non-nullable variable before it is used, useful for values initialized after declaration.
String name = 'Ada'; // must have a value String? nickname; // allowed to be null late String id; // will be assigned before first use nickname = null; // OK, it is nullable print(nickname?.length ?? 0); // 0 when null

Control Flow

// if / else if (score >= 90) { print('A'); } else if (score >= 60) { print('Pass'); } else { print('Fail'); } // switch switch (day) { case 'Sat': case 'Sun': print('Weekend'); break; default: print('Weekday'); } // loops for (var i = 0; i < 3; i++) print(i); for (var item in items) print(item); // for-in while (n > 0) n--;
  • Ternary : var result = score >= 60 ? 'Pass' : 'Fail';
  • break / continue : Exit a loop early or skip to the next iteration.

Collections

// List (ordered) var nums = [1, 2, 3]; nums.add(4); print(nums[0]); // 1 // Set (unique, unordered) var tags = {'a', 'b', 'a'}; // {a, b} // Map (key-value) var user = {'name': 'Ada', 'age': 36}; print(user['name']); // Ada
Useful Methods -
  • map : Transform each element: nums.map((n) => n * 2).
  • where : Filter elements: nums.where((n) => n.isEven).
  • forEach : Run code for each element.
  • reduce / fold : Combine elements into one value.
Spread & Collection-If -
var a = [1, 2]; var b = [0, ...a, 3]; // [0, 1, 2, 3] spread var list = [ 'always', if (isAdmin) 'admin', // collection-if for (var n in a) 'item$n', // collection-for ];

Functions

// standard function int add(int a, int b) { return a + b; } // arrow function (single expression) int square(int x) => x * x;
Parameters -
  • Positional : Passed in order, like add(2, 3).
  • Named : Wrapped in { }, passed by name for clarity. Mark required ones with required.
  • Optional Positional : Wrapped in [ ], can be left out.
  • Default Values : Give a fallback: greet({String name = 'Guest'}).
// named parameters String greet({required String name, String greeting = 'Hi'}) { return '$greeting, $name'; } greet(name: 'Ada'); // "Hi, Ada" greet(name: 'Ada', greeting: 'Hello');
  • First-Class Functions : Functions can be stored in variables, passed as arguments, and returned. Anonymous functions (lambdas) use (x) { ... } or arrow syntax.

Classes & OOP

Dart is fully object-oriented. Classes bundle data (fields) and behavior (methods), and support inheritance, interfaces, and mixins.

class Person { String name; int age; // constructor (shorthand assigns to fields) Person(this.name, this.age); // named constructor Person.guest() : name = 'Guest', age = 0; // method void greet() => print('Hi, I am $name'); } var p = Person('Ada', 36); p.greet();
OOP Concepts -
  • Inheritance : extends a parent class; use super to call its constructor and @override to replace a method.
  • Abstract Class : A base class that cannot be instantiated and may declare methods without bodies.
  • Interface : Any class can be an interface via implements, which forces the class to define all its members.
  • Mixin : Reuse methods across unrelated classes with with, without inheritance.
  • Getters / Setters : Custom property access with get and set.
  • Encapsulation : A leading underscore (_field) makes a member private to its file (library).
  • static : Members that belong to the class itself, not to instances.
class Student extends Person { String school; Student(String name, int age, this.school) : super(name, age); @override void greet() => print('$name studies at $school'); }

Async

Dart handles operations that take time (network calls, file reads) without blocking, using Futures and async/await.

  • Future : A value that will be available later, like a JavaScript promise. It is either completed with a value or an error.
  • async / await : Mark a function async and use await to pause until a Future completes, writing async code that reads like synchronous code.
  • Stream : A sequence of async values over time (like multiple Futures), consumed with await for or .listen(). Used for things like user events or live data.
Future<String> fetchUser() async { await Future.delayed(Duration(seconds: 1)); // simulate delay return 'Ada'; } void main() async { print('Loading...'); var user = await fetchUser(); print('Got: $user'); }

Generics & Exceptions

Generics -

Generics let a class or function work with any type while staying type-safe, using a type parameter like <T>. Built-in collections use them: List<int>, Map<String, int>.

T first<T>(List<T> items) => items[0]; first<int>([1, 2, 3]); // 1 first(['a', 'b']); // 'a', type inferred
Exceptions -

Handle errors with try / catch, optionally finally for cleanup that always runs. Throw errors with throw.

try { var result = 10 ~/ 0; // throws } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } catch (e) { print('Error: $e'); } finally { print('Always runs'); } throw Exception('Something went wrong');