Dart Generics
Dart Generics
Generics let you write code that works with many types, but is still type-safe.
Type-safe means that Dart checks the types for you, and stops you if you use a wrong type.
You have already used generics with lists and maps.
The type inside the angle brackets <> is called a type argument:
Example
void main() {
List<String> fruits = ['apple', 'banana'];
Map<String, int> ages = {'John': 36, 'Anna': 28};
fruits.add('cherry');
ages['Linus'] = 41;
print(fruits);
print(ages);
}
Try it Yourself »
Result:
[apple, banana, cherry]
{John: 36, Anna: 28, Linus: 41}
List<String> is a list that can only hold strings.
If you try to add a number, you get an error:
Example
void main() {
List<String> fruits = ['apple', 'banana'];
fruits.add(42);
print(fruits);
}
Try it Yourself »
Result:
main.dart:3:14: Error: The argument type 'int' can't be assigned to the parameter type 'String'.
fruits.add(42);
^
You can also write the type argument on the value instead of the variable:
Example
void main() {
var scores = <int>[];
var prices = <String, double>{};
scores.add(90);
prices['milk'] = 1.25;
print(scores);
print(prices);
}
Try it Yourself »
Result:
[90]
{milk: 1.25}
Generic Classes
You can write your own generic class.
Put a type parameter in angle brackets after the class name.
By convention, the type parameter is a single capital letter, like T (for "type").
Inside the class, T stands for the real type that is used later:
Example
class Box<T> {
T content;
Box(this.content);
T open() {
return content;
}
}
void main() {
var stringBox = Box<String>('A gift');
var intBox = Box<int>(100);
print(stringBox.open());
print(intBox.open());
}
Try it Yourself »
Result:
A gift
100
The same Box class works for strings, numbers and any other type.
A Box<int> can only hold an int:
Example
class Box<T> {
T content;
Box(this.content);
}
void main() {
var intBox = Box<int>(100);
intBox.content = 'hello';
print(intBox.content);
}
Try it Yourself »
Result:
main.dart:9:20: Error: A value of type 'String' can't be assigned to a variable of type 'int'.
intBox.content = 'hello';
^
Tip: You can often leave out the type argument, and Dart works it out from the value.
Box('A gift') creates a Box<String>.
Several Type Parameters
A class can have more than one type parameter.
Separate them with commas, like in Map<K, V>:
Example
class Pair<A, B> {
A first;
B second;
Pair(this.first, this.second);
void show() {
print('$first and $second');
}
}
void main() {
var p1 = Pair<String, int>('Apples', 5);
var p2 = Pair<bool, double>(true, 3.14);
p1.show();
p2.show();
}
Try it Yourself »
Result:
Apples and 5
true and 3.14
Generic Functions
A function can also have a type parameter.
Write it in angle brackets after the function name:
Example
T firstItem<T>(List<T> items) {
return items[0];
}
void main() {
var names = ['Liam', 'Olivia', 'Noah'];
var numbers = [7, 3, 9];
String name = firstItem(names);
int number = firstItem(numbers);
print(name);
print(number);
}
Try it Yourself »
Result:
Liam
7
The function returns a String for a list of strings, and an int for a list of integers.
Bounded Types
Sometimes a type parameter should only allow some types.
Use extends to set a limit, called a bound.
T extends num means that T must be num or a type of number, like int or double:
Example
T biggest<T extends num>(List<T> values) {
var max = values[0];
for (var value in values) {
if (value > max) {
max = value;
}
}
return max;
}
void main() {
print(biggest([4, 12, 7]));
print(biggest([2.5, 1.5, 9.75]));
}
Try it Yourself »
Result:
12
9.75
Because T is always a number, the code can use > on the values.
If you use a type that is not a number, you get an error:
Example
T biggest<T extends num>(List<T> values) {
var max = values[0];
for (var value in values) {
if (value > max) {
max = value;
}
}
return max;
}
void main() {
print(biggest(['cat', 'dog']));
}
Try it Yourself »
Result:
main.dart:12:18: Error: A value of type 'String' can't be assigned to a variable of type 'num'.
print(biggest(['cat', 'dog']));
^
main.dart:12:25: Error: A value of type 'String' can't be assigned to a variable of type 'num'.
print(biggest(['cat', 'dog']));
^