Sub topic 2
Functions, Collections, Classes, and Inheritance in Dart
This chapter assumes you can write a basic Dart program with main(), variables, and if statements, and that you understand classes and objects from another language.
Functions, named parameters, and closures
Dart functions take positional parameters, which are matched by order, and named parameters, which are written inside {} and matched by name. Named parameters can have default values.
String format(String name, {String greeting = 'Hello', bool shout = false}) {
final text = '$greeting, $name!';
return shout ? text.toUpperCase() : text;
}
int Function() makeCounter() {
var count = 0;
return () => ++count;
}
void main() {
print(format('Ada'));
print(format('Ada', greeting: 'Hi', shout: true));
final next = makeCounter();
next();
print(next());
}A closure is a function that keeps access to variables from the scope where it was created. Each call to makeCounter() creates a separate count.
Lists, Sets, and Maps
A List keeps order and allows duplicates. A Set has no duplicates. A Map stores key and value pairs.
| Type | Literal | Duplicates | Ordered by |
|---|---|---|---|
| List | `[1, 2]` | Allowed | Insertion |
| Set | `{1, 2}` | Not allowed | Insertion (LinkedHashSet) |
| Map | `{'a': 1}` | Keys unique | Insertion |
Classes and constructors
Use this.field in the constructor to assign fields directly. A const constructor allows compile-time constant instances. Named constructors and redirecting constructors use : this(...).
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin() : this(0, 0);
}Inheritance, abstract classes, and mixins
An abstract class cannot be instantiated and can declare members that subclasses must implement. A mixin adds behavior to a class that uses with.
mixin Walker {
void walk() => print('$runtimeType walks');
}
abstract class Animal {
final String name;
Animal(this.name);
String sound();
}
class Dog extends Animal with Walker {
Dog(super.name);
@override
String sound() => 'Woof';
}Enums and extension methods
An enhanced enum can hold fields. An extension adds methods or getters to an existing type without subclassing it.
enum Planet {
earth(9.8),
mars(3.7);
const Planet(this.gravity);
final double gravity;
}
extension StringShout on String {
String get shout => '${toUpperCase()}!';
}Exercise
Given Planet.mars, what does Planet.mars.gravity return, and why can Planet values not be created with new outside the enum?
Show answer
It returns 3.7. Enum values are fixed constants declared inside the enum, so other code uses the named values instead of constructing new ones.