Functions, Collections, and Classes
Functions and Parameters
A function is a named piece of code that does a job and can give back a result. Dart functions say what type of result they return. You can pass values in, give them names with defaults, and even pass other functions.
int add(int a, int b) => a + b;
void greet(String name, {String prefix = 'Hello'}) {
print('$prefix, $name!');
}
void runTwice(void Function() action) {
action();
action();
}
void main() {
greet('Ada'); // Hello, Ada!
runTwice(() => print('tick')); // tick tick
}Lists, Sets, and Maps
Dart has three everyday containers:
- List — an ordered row of items, like a shopping list.
- Set — items where each one appears only once.
- Map — pairs of keys and values, like a phone book.
var names = ['Ada', 'Alan'];
var unique = {'a', 'b', 'a'}; // only one 'a'
var ages = {'Ada': 39, 'Alan': 41};
print(ages['Ada']); // 39Mapping, Filtering, and Reducing
These are ways to transform a collection: map changes each item, filter (called where in Dart) keeps some items, and reduce squashes everything into one result.
final upper = names.map((n) => n.toUpperCase()).toList();
print(upper); // [ADA, ALAN]Classes and Objects
A class is a blueprint. An object is one thing built from that blueprint. A class holds data and the actions that work with it.
class Counter {
int _count = 0; // _count is private to this file
int get count => _count;
void increment() => _count++;
@override
String toString() => 'Counter($_count)';
}Constructors, Fields, and Methods
A constructor is the special recipe for building an object. Fields are the variables inside, and methods are the actions. Writing Circle(this.radius) saves a value straight into a field.
class Circle {
final double radius;
Circle(this.radius);
}Inheritance and Overriding
Inheritance lets one class build on another. The child gets the parent's abilities and can override — replace — any it wants to do differently.
class Animal {
void speak() => print('...');
}
class Dog extends Animal {
@override
void speak() => print('Woof!');
}Exercise
What does where do on a list?
Show answer
It filters the list, keeping only the items for which its test returns true.
Spotted a mistake, or code that does not work?