Sub topic 11
Generics
Why use generics?
This chapter assumes you understand variables, functions, classes, and basic null safety. Generics let you write reusable code while preserving information about the type of each value.
A generic type contains a type parameter, such as T. The caller supplies a concrete type for T, such as String or int.
Without generics, a reusable container might use Object or dynamic. That weakens compile-time checking. With generics, Dart can reject invalid values before the program runs.
T firstOr<T>(List<T> items, T fallback) =>
items.isEmpty ? fallback : items.first;
class Box<T extends num> {
final T value;
Box(this.value);
double doubled() => value.toDouble() * 2;
}
void main() {
print(firstOr<String>([], 'none'));
print(firstOr([10, 20], 0));
final box = Box(21);
print(box.doubled());
}firstOr<T> is a generic function. Its list and fallback must use the same type. firstOr<String> explicitly chooses String, but Dart can infer int in firstOr([10, 20], 0).
Box<T extends num> is a generic class with a bound. The bound says that T must be num or one of its subtypes, such as int or double. This lets the class safely call numeric operations after converting the value.
Inference and explicit type arguments
Dart often infers a type from the arguments:
final names = <String>['Ada', 'Linus'];
final scores = <String, int>{'Ada': 10};The angle brackets specify type arguments. The first declaration creates a List<String>. The second creates a Map<String, int>.
You can also write final names = ['Ada', 'Linus'];. Dart infers List<String> from the values. Use explicit type arguments when an empty collection or a complex expression does not provide enough information.
| Generic form | Meaning | Example |
|---|---|---|
| `List<T>` | A sequence of values of type `T` | `List<int>` |
| `Map<K, V>` | Keys of type `K`, values of type `V` | `Map<String, int>` |
| `T extends num` | `T` must satisfy a bound | `Box<double>` |
Common errors
An unconstrained type parameter does not promise that values support a particular operation:
// This is invalid because T might be String.
double bad<T>(T value) => value * 2;Add a bound when the operation requires one. Also remember that List<int> and List<String> are different types. A function that accepts List<String> should not receive a list of integers.
A generic class can have more than one parameter:
class Pair<Left, Right> {
final Left left;
final Right right;
Pair(this.left, this.right);
}Generics combine especially well with collections and functions. They allow one implementation to serve many types without giving up static checking.
Exercise
What type does firstOr([1, 2], 0) use for T, and why is Box('text') rejected?
Show answer
T is inferred as int from the list and fallback. Box('text') is rejected because Box requires T to extend num.