Dart Generics
Generics let you write classes and functions that work with any type while staying type-safe. You've been using them all along: List<String>, Map<String, int> and Future<User> are generic types with type arguments in angle brackets.
Why generics?
Without generics, a reusable container would have to store Object?, and every read would need a cast that might fail at runtime. With a type parameter, the compiler knows exactly what's inside:
class Box<T> {
T value;
Box(this.value);
Box<R> map<R>(R Function(T) transform) => Box(transform(value));
@override
String toString() => 'Box<$T>($value)';
}
void main() {
final age = Box(30); // Box<int> inferred
final name = Box<String>('Uyen');
int years = age.value; // no cast needed
print(years + 1);
print(name.value.toUpperCase());
final label = age.map((n) => 'age $n');
print(label);
print(label.value.length);
}31
UYEN
Box<String>(age 30)
6
T and R are type parameters. Conventional names: T (type), E (element), K/V (key/value), R (result).
Generic functions
T firstOr<T>(List<T> items, T fallback) => items.isEmpty ? fallback : items.first;
Map<K, List<V>> groupBy<K, V>(Iterable<V> items, K Function(V) keyOf) {
final result = <K, List<V>>{};
for (final item in items) {
result.putIfAbsent(keyOf(item), () => []).add(item);
}
return result;
}
void main() {
print(firstOr(<int>[], -1));
print(firstOr(['x', 'y'], 'none'));
final words = ['ant', 'bee', 'cat', 'bird', 'cow'];
print(groupBy(words, (w) => w[0]));
print(groupBy(words, (w) => w.length));
}-1
x
{a: [ant], b: [bee, bird], c: [cat, cow]}
{3: [ant, bee, cat, cow], 4: [bird]}
Type arguments are usually inferred from the arguments; write them explicitly (firstOr<int>(...)) when inference can't work it out, such as with an empty literal.
Bounded type parameters
T extends SomeType restricts which types may be used and lets the generic code call that type's members:
abstract class Entity {
int get id;
}
class Customer implements Entity {
@override
final int id;
final String name;
Customer(this.id, this.name);
@override
String toString() => 'Customer($id, $name)';
}
class Repository<T extends Entity> {
final _items = <int, T>{};
void save(T item) => _items[item.id] = item; // .id is available thanks to the bound
T? find(int id) => _items[id];
List<T> get all => _items.values.toList();
}
T largest<T extends Comparable<T>>(List<T> items) =>
items.reduce((a, b) => a.compareTo(b) >= 0 ? a : b);
void main() {
final repo = Repository<Customer>()
..save(Customer(1, 'Dung'))
..save(Customer(2, 'Hieu'));
print(repo.find(2));
print(repo.find(9));
print(repo.all.length);
print(largest(<num>[3, 17, 8])); // int is Comparable<num>, so use num
print(largest(['pear', 'apple', 'plum']));
}Customer(2, Hieu)
null
2
17
plum
Repository<String> would be a compile error, since String isn't an Entity.
Reified generics
Unlike Java, Dart generics are reified: type arguments are kept at runtime. You can check them with is and print them:
void main() {
final names = <String>['a', 'b'];
final Object any = names;
print(any is List<String>);
print(any is List<int>);
print(names.runtimeType);
print(typeName<double>());
}
String typeName<T>() => 'T is $T';true
false
List<String>
T is double
Variance in practice
Dart's generic classes are covariant: a List<Cat> is a List<Animal>. That's convenient, but writing an Animal into it is checked at runtime:
class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}
void main() {
List<Cat> cats = [Cat()];
List<Animal> animals = cats; // allowed: covariance
print(animals.length);
try {
animals.add(Dog()); // runtime check fails
} on TypeError {
print('TypeError: a Dog cannot go into a List<Cat>');
}
}1
TypeError: a Dog cannot go into a List<Cat>
Generics cheat sheet
| Syntax | Meaning |
|---|---|
class Box<T> |
Generic class |
T pick<T>(…) |
Generic function / method |
<T extends num> |
Upper bound |
<T extends Object> |
Non-nullable type argument |
<String>[], <int, bool>{} |
Explicit type arguments on literals |
typedef Json = Map<String, Object?>; |
Name a generic instantiation |
Tip: Avoid raw types like
Listwithout arguments — they becomeList<dynamic>and silently disable type checks.
Test yourself
What does <T extends num> mean?
- T must be exactly num
- T must be num or a subtype like int or double
- T can be any type
- T is nullable
Does <String>['a'] is List<int> evaluate to true?
- Yes, generics are erased
- No — Dart generics are reified, so it's false
- Compile error
- Throws at runtime
What is the type of Box(3.5) given class Box<T> { T value; Box(this.value); }?
- Box<dynamic>
- Box<num>
- Box<double>
- Box<Object>