Dart: reference

The language of Flutter: one codebase for Android, iOS and the web, null safety and async code.

Program structure

Minimal program

Execution starts in the main function. print prints a line and moves to a new one. Every statement ends with a semicolon.

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

Build and run

dart create creates a project, dart run runs it or a single file, and dart compile exe builds a standalone executable file.

dart create my_app
cd my_app
dart run

dart run hello.dart
dart compile exe bin/my_app.dart

Variables and types

var, final and const

var infers the type itself, but the type cannot be changed afterwards. final is set once at run time, and const is a compile-time constant.

void main() {
  var name = 'Olena';
  int score = 0;
  score += 10;
  final age = 16;
  const pi = 3.14;
  print('$name $score $age $pi');
}

Basic types

Main types: int, double, String, bool. The num type unites int and double. The runtimeType value shows the type at run time.

void main() {
  int i = 42;
  double d = 3.14;
  String s = 'text';
  bool ok = true;
  num n = 5;
  n = 2.5;
  print('${i.runtimeType} ${d.runtimeType} $n $ok $s');
}

Type conversion

The / operator always gives a double, and ~/ is integer division. int.tryParse returns null instead of an error, while int.parse throws an exception.

void main() {
  int a = int.parse('12');
  int? b = int.tryParse('abc');
  double d = 7 / 2;
  int q = 7 ~/ 2;
  String s = 42.toString();
  double e = 3.toDouble();
  print('$a $b $d $q $s $e');
}

Records

A record is a lightweight group of values in parentheses. Named fields are accessed with a dot, positional ones with $1, $2. A record can be unpacked into variables.

void main() {
  var (x, y) = (3, 4);
  print(x + y);
  var user = (name: 'Olena', age: 16);
  print(user.name);
  var pair = (1, 'one');
  print(pair.$1);
}

Strings

Interpolation

$name inserts a variable into a string, and ${expression} evaluates an arbitrary expression. You can use either single or double quotes.

void main() {
  var name = 'Dart';
  var a = 3;
  var b = 4;
  print('Hello, $name!');
  print('Sum: ${a + b}');
  print('Length: ${name.length}');
}

String methods

Strings are immutable: methods return a new string. length is a property, so there are no parentheses after it. The split method returns a list.

void main() {
  var s = 'Hello, World';
  print(s.length);
  print(s.toUpperCase());
  print(s.substring(0, 5));
  print(s.replaceAll('World', 'Dart'));
  print(s.contains('World'));
  print(s.split(', '));
}

Multiline and raw strings

Triple quotes let you write a string over several lines. The r prefix makes a string raw: backslashes are not escaped. The * operator repeats a string.

void main() {
  var text = '''Line one
Line two''';
  print(text);
  var path = r'C:\new\dir';
  print(path);
  print('ab' * 3);
}

Conditions

if and the ternary operator

The condition goes in parentheses and must be of type bool: 0 or an empty string are not treated as false. The short form is condition ? a : b.

void main() {
  var age = 16;
  if (age < 12) {
    print('child');
  } else if (age < 18) {
    print('teen');
  } else {
    print('adult');
  }
  var status = age >= 18 ? 'adult' : 'minor';
  print(status);
}

switch as an expression

In Dart 3 a switch can return a value. Branches are written with =>, several values are joined with ||, and _ is the default branch.

void main() {
  var day = 6;
  var kind = switch (day) {
    1 || 2 || 3 || 4 || 5 => 'weekday',
    6 || 7 => 'weekend',
    _ => 'unknown',
  };
  print(kind);
}

Patterns and conditions in switch

Patterns compare a value with a condition: >= 90 checks a range. The case int n when ... construct checks the type, stores the value in n and adds a condition.

String grade(int n) => switch (n) {
  >= 90 => 'A',
  >= 50 => 'B',
  _ => 'F',
};

void main() {
  print(grade(95));
  Object x = 5;
  if (x case int n when n > 3) print('big $n');
}

Loops

for and for-in

The classic for has an initializer, a condition and a step. The for-in loop walks over the elements of a collection, and forEach takes a function for each element.

void main() {
  for (var i = 0; i < 3; i++) {
    print(i);
  }
  for (var f in ['apple', 'pear']) {
    print(f);
  }
  [1, 2].forEach((n) => print(n * 10));
}

while and do-while

while checks the condition before each pass, and do-while after it, so its body runs at least once.

void main() {
  var n = 3;
  while (n > 0) {
    print(n);
    n--;
  }
  do {
    n++;
  } while (n < 3);
  print(n);
}

break and continue

break leaves the loop immediately, and continue skips the rest of the current iteration. The isOdd property checks whether a number is odd.

void main() {
  for (var i = 0; i < 10; i++) {
    if (i.isOdd) continue;
    if (i > 6) break;
    print(i);
  }
}

Functions

Declaration and arrow

The return type is written before the name, and void means there is no value. The => expression form is a shorthand for a function with a single return.

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

int square(int x) => x * x;

void main() {
  print(add(2, 3));
  print(square(4));
}

Optional and named parameters

Positional parameters in [ ] can be omitted. Parameters in { } are passed by name, and required makes such a parameter mandatory.

String greet(String name, [String hi = 'Hello']) => '$hi, $name!';

String connect({required String host, int port = 80}) => '$host:$port';

void main() {
  print(greet('Ann'));
  print(greet('Ann', 'Hi'));
  print(connect(host: 'localhost', port: 8080));
}

Functions as values

A function can be passed as an argument. The methods map, where and fold take a lambda. A function parameter's type is written as int Function(int).

void apply(int x, int Function(int) f) => print(f(x));

void main() {
  var nums = [1, 2, 3, 4];
  print(nums.map((n) => n * n).toList());
  print(nums.where((n) => n.isEven).toList());
  print(nums.fold(0, (a, b) => a + b));
  apply(3, (v) => v + 1);
}

Collection literals

List

A list is created with the [ ] literal. The add method appends an element, sort sorts in place, and first and last give the edge elements.

void main() {
  var a = [3, 1, 2];
  a.add(4);
  a.addAll([5, 6]);
  a.sort();
  print(a);
  print(a.length);
  print('${a.first} ${a.last} ${a[1]}');
  print(a.contains(2));
}

Map

A Map stores key and value pairs. A missing key gives null. Pairs are traversed with forEach or via entries, which have key and value.

void main() {
  Map<String, int> prices = {'apple': 3, 'pear': 5};
  prices['plum'] = 7;
  print(prices['apple']);
  print(prices['none']);
  print(prices.containsKey('pear'));
  prices.forEach((k, v) => print('$k = $v'));
  for (var e in prices.entries) {
    print(e.key);
  }
}

Set and spread

A set { } has no duplicates. The ... operator spreads one collection into another, and if and for inside a literal add elements conditionally.

void main() {
  var s = {1, 2, 3};
  s.add(2);
  print(s.length);
  var base = [1, 2];
  var more = [...base, 3, 4];
  var admin = true;
  var menu = ['home', if (admin) 'admin', for (var i in base) 'item$i'];
  print(more);
  print(menu);
}

Classes and enum

Class and constructor

The Person(this.name, this.age) form assigns fields directly from the parameters. The named constructor Person.baby is another way to create an object, and get declares a computed property.

class Person {
  final String name;
  int age;
  Person(this.name, this.age);
  Person.baby(this.name) : age = 0;

  String get info => '$name ($age)';
  void birthday() => age++;
}

void main() {
  var p = Person('Olena', 16);
  p.birthday();
  print(p.info);
  print(Person.baby('Ann').age);
}

Inheritance and abstract

extends names the parent class, and @override marks an overridden method. An abstract class cannot be instantiated directly, it only defines a contract.

abstract class Animal {
  String speak();
}

class Dog extends Animal {
  @override
  String speak() => 'Woof!';
}

void main() {
  Animal a = Dog();
  print(a.speak());
}

enum

enum describes a fixed set of values, values returns them as a list, and name gives the name. An enum can have fields and a constructor.

enum Color { red, green, blue }

enum Planet {
  earth(1.0),
  mars(0.38);

  final double gravity;
  const Planet(this.gravity);
}

void main() {
  print(Color.red.name);
  print(Color.values.length);
  print(Planet.mars.gravity);
}

Null safety

Types with ? and operators

A type with ?, for example String?, can be null. The ?. operator calls a method safely, ?? gives a fallback value, and ! asserts that the value is not null.

String? find(bool ok) => ok ? 'Olena' : null;

void main() {
  String? a = find(false);
  String? b = find(true);
  print(a);
  print(a?.length);
  print(a ?? 'unknown');
  print(b!.length);
}

Null check and late

After the s == null check the compiler knows s is not null and allows s.length. The late keyword defers initialization until first use.

late String config;

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

void main() {
  show(null);
  show('abc');
  config = 'ready';
  print(config);
}

async/await and Future

Future, async and await

A Future is a value that will appear later. A function with async returns a Future, and await waits for the result without blocking the rest of the program.

Future<String> fetchName() async {
  await Future.delayed(Duration(milliseconds: 100));
  return 'Olena';
}

Future<void> main() async {
  print('start');
  var name = await fetchName();
  print(name);
}

Future.wait and errors

Future.wait waits for all operations and returns a list of results. An error from a future can be caught with an ordinary try/catch around await.

Future<int> parse(String s) async => int.parse(s);

Future<void> main() async {
  var all = await Future.wait([parse('1'), parse('2')]);
  print(all);
  try {
    print(await parse('abc'));
  } catch (e) {
    print('error: $e');
  }
}

Stream

A Stream delivers a sequence of values over time. An async* generator emits them with yield, and an await for loop receives the values one by one.

Stream<int> count(int n) async* {
  for (var i = 1; i <= n; i++) {
    yield i;
  }
}

Future<void> main() async {
  await for (var v in count(3)) {
    print(v);
  }
}

Errors

try, on, catch, finally

on Type catches an error of a given class, and catch (e) any other. The finally block always runs, whether or not there was an error.

void main() {
  try {
    print(int.parse('abc'));
  } on FormatException {
    print('Format error');
  } catch (e) {
    print('other: $e');
  } finally {
    print('done');
  }
}

throw and custom exceptions

throw raises an exception. A custom exception class is written with implements Exception, and on ... catch (e) gives access to the error object.

class NegativeException implements Exception {
  final String message;
  NegativeException(this.message);
}

void check(int x) {
  if (x < 0) throw NegativeException('negative: $x');
}

void main() {
  try {
    check(-1);
  } on NegativeException catch (e) {
    print(e.message);
  }
}

What is next

A lessons course for this language is on the way, and the reference is already available.

A course is on the way. For now only the reference is available; lessons and tasks will follow.