Generics
suggest changeGenerics let you write a class, function or type alias once and use it with many different types, while keeping full static type checking. You already use them all the time: List<String>, Map<String, int>, Future<User> and Stream<List<int>> are all generic types instantiated with a type argument.
Without generics you have two bad choices: write a separate IntStack, StringStack, UserStack, or write one stack of Object? and cast everything that comes out of it. Generics give you one implementation and no casts.
Dart generics have two properties worth knowing up front:
- They are reified: type arguments are kept at runtime, so
list is List<int>actually checks the element type. - Generic classes are covariant: a
List<int>can be used where aList<num>is expected. This is convenient but needs a runtime check, covered below.
Generic classes
Declare type parameters in angle brackets after the class name. By convention they are single uppercase letters: T (type), E (element), K and V (key and value), R (result).
The first class below stores an Object? and forces callers to cast. The generic Box<T> remembers what it holds:
class ObjectBox {
Object? value;
ObjectBox(this.value);
}
class Box<T> {
T value;
Box(this.value);
}
void main() {
final ob = ObjectBox('hello');
// ob.value.length; // compile error: length isn't defined for Object?
print((ob.value as String).length);
final b = Box('hello'); // inferred as Box<String>
print(b.value.length);
// b.value = 42; // compile error: int can't be assigned to String
final n = Box<int>(10);
n.value += 5;
print(n.value);
print(b.runtimeType);
print(n.runtimeType);
}
Output:
5
5
15
Box<String>
Box<int>
Note that Box('hello') didn't need <String>: the type argument was inferred from the constructor argument. The commented-out lines are errors the analyzer reports before the program runs.
A more realistic example is a stack. The type parameter E is used for fields, parameters, return types and even inside a collection literal:
class Stack<E> {
final _items = <E>[];
void push(E item) => _items.add(item);
E pop() {
if (_items.isEmpty) throw StateError('stack is empty');
return _items.removeLast();
}
E? get top => _items.isEmpty ? null : _items.last;
bool get isEmpty => _items.isEmpty;
int get length => _items.length;
@override
String toString() => 'Stack$_items';
}
void main() {
final s = Stack<String>();
s.push('a');
s.push('b');
s.push('c');
print(s);
print(s.pop());
print(s.top);
print(s.length);
}
Output:
Stack[a, b, c]
c
b
2
Generic functions and methods
Functions and methods can have their own type parameters, declared after the name. Dart infers them from the arguments, so callers rarely write them:
T firstOr<T>(List<T> items, T fallback) =>
items.isEmpty ? fallback : items.first;
(B, A) swap<A, B>((A, B) pair) => (pair.$2, pair.$1);
List<R> mapAll<T, R>(Iterable<T> items, R Function(T) f) =>
[for (final item in items) f(item)];
void main() {
print(firstOr([3, 1, 2], 0));
print(firstOr(<String>[], 'none'));
final swapped = swap(('id', 42));
print(swapped);
print(swapped.runtimeType);
final lengths = mapAll(['one', 'three'], (s) => s.length);
print(lengths);
print(lengths.runtimeType);
// explicit type arguments
final d = firstOr<num>([1, 2], 2.5);
print('$d ${d.runtimeType}');
}
Output:
3
none
(42, id)
(int, String)
[3, 5]
List<int>
1 int
In the last call the explicit <num> is needed: without it, Dart would complain that 2.5 isn't an int. With T = num both int and double arguments are fine.
Type parameters of a function are independent of any type parameters of the enclosing class. A method can introduce new ones, as flip does with the class's own parameters swapped:
class Pair<K, V> {
final K key;
final V value;
const Pair(this.key, this.value);
Pair<V, K> flip() => Pair(value, key);
@override
String toString() => '($key, $value)';
}
void main() {
const p = Pair('port', 8080);
print(p);
print(p.flip());
print(p.flip().runtimeType);
}
Output:
(port, 8080)
(8080, port)
Pair<int, String>
For an ad-hoc pair you'd often use a record such as (String, int) instead (see Destructuring). A named generic class is better when the pair has behavior or appears in many APIs.
Restricting type parameters with extends
An unrestricted T can be anything, so inside the function you can only use members that every object has (toString, ==, hashCode). A bound, written T extends SomeType, restricts the allowed type arguments and in exchange lets you call that type's members:
T larger<T extends num>(T a, T b) => a > b ? a : b;
T maxOf<T extends Comparable<T>>(List<T> items) {
var best = items.first;
for (final item in items.skip(1)) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
class Version implements Comparable<Version> {
final int major, minor;
const Version(this.major, this.minor);
@override
int compareTo(Version other) =>
major != other.major ? major - other.major : minor - other.minor;
@override
String toString() => '$major.$minor';
}
void main() {
int i = larger(3, 7);
double d = larger(2.5, 1.0);
print('$i $d');
// larger('a', 'b'); // compile error: String doesn't conform to the bound num
print(maxOf([3, 9, 4]));
print(maxOf(['pear', 'apple', 'zucchini']));
print(maxOf([Version(1, 4), Version(2, 0), Version(1, 10)]));
}
Output:
7 2.5
9
zucchini
2.0
T extends Comparable<T> is the standard bound for "anything that can be ordered". int, double, String, DateTime and Duration all implement Comparable, and so does any class of yours that implements compareTo (see Equality and comparison and Sorting).
larger shows why a bound is better than just taking num: the result keeps the precise type. larger(3, 7) returns an int, not a num, so it can be assigned to an int variable without a cast.
A common bound is T extends Object, which means "any non-nullable type". By default a type parameter allows nullable types too, because its implicit bound is Object?.
Generic collection literals and inference
Collection literals take type arguments in front of the brackets: <int>[], <String>{}, <String, int>{}. When the literal isn't empty Dart infers the type from the elements, picking the closest common supertype:
class Box<T extends num> {
final T value;
Box(this.value);
}
void main() {
final a = [];
print(a.runtimeType);
final c = [1, 2.5];
print(c.runtimeType);
final d = [1, 'two', null];
print(d.runtimeType);
Box raw = Box(3); // type argument omitted: instantiated to bound
print(raw.runtimeType);
final e = <int>[]..add(1);
// e.add('x'); // compile error
print(e);
}
Output:
List<dynamic>
List<num>
List<Object?>
Box<num>
[1]
Two things to watch for:
- An empty literal with no context type is
List<dynamic>orMap<dynamic, dynamic>. Dynamic collections silently turn off type checking, so write<int>[]or give the variable a type. - When you write a generic type without type arguments, like
Boxabove, Dart fills in the bound of each type parameter (numhere, ordynamicwhen there's no bound). This is called instantiate-to-bounds. Thestrict-raw-typesanalyzer option makes this a warning.
Reified generics: types at runtime
Unlike Java, where List<String> becomes just List after compilation, Dart keeps type arguments at runtime. You can test them with is, print them, and use a type parameter as a value inside a generic function:
void describe(Object o) {
if (o is List<int>) {
print('list of ints, sum = ${o.fold(0, (a, b) => a + b)}');
} else if (o is List<String>) {
print('list of strings: ${o.join('+')}');
} else if (o is List) {
print('some other list: ${o.runtimeType}');
}
}
String typeName<T>() => '$T';
bool isNullableType<T>() => null is T;
void main() {
describe([1, 2, 3]);
describe(['a', 'b']);
describe([1, 'a']);
print(typeName<Map<String, int>>());
print(isNullableType<int>());
print(isNullableType<int?>());
final untyped = []; // List<dynamic>
print(untyped.runtimeType);
final explicit = <double>[];
print(explicit.runtimeType);
}
Output:
list of ints, sum = 6
list of strings: a+b
some other list: List<Object>
Map<String, int>
false
true
List<dynamic>
List<double>
Note the third call: [1, 'a'] is a List<Object>, not List<int> or List<String>, so only the last branch matches. null is T is a neat trick to check at runtime whether T is a nullable type.
Reification is what makes generic code like JSON helpers or dependency-injection containers possible. Here a registry uses T as a key in a map of factories:
class Registry {
final _factories = <Type, Object Function()>{};
void register<T extends Object>(T Function() create) {
_factories[T] = create;
}
T create<T extends Object>() {
final f = _factories[T];
if (f == null) throw StateError('no factory for $T');
return f() as T;
}
}
class Logger {}
class Clock {
DateTime now() => DateTime.utc(2026, 10, 17);
}
void main() {
final r = Registry();
r.register(Logger.new);
r.register<Clock>(() => Clock());
final clock = r.create<Clock>();
print(clock.now());
print(r.create<Logger>().runtimeType);
try {
r.create<String>();
} on StateError catch (e) {
print(e.message);
}
}
Output:
2026-10-17 00:00:00.000Z
Logger
no factory for String
What you can't do with a type parameter is call a constructor through it: T() is not valid Dart. The usual workaround is the one used above: pass a factory function such as Logger.new or () => Clock().
Covariance and runtime checks
Generic classes in Dart are covariant: if int is a subtype of num, then List<int> is a subtype of List<num>. Reading from such a list is always safe, but writing isn't, so the VM checks every write at runtime:
void addOne(List<num> numbers) {
numbers.add(1.5);
}
void main() {
final ints = <int>[1, 2];
List<num> nums = ints; // allowed: List<int> is a subtype of List<num>
print(nums is List<int>);
try {
addOne(ints);
} on TypeError catch (e) {
print('TypeError: $e');
}
print(ints);
}
Output:
true
TypeError: type 'double' is not a subtype of type 'int' of 'value'
[1, 2]
addOne looks correct to the analyzer because it only sees a List<num>. The object, however, is still a List<int>, and adding a double to it fails. The Common pitfalls article describes this trap in more detail.
The practical rules:
- If a function only reads from a collection, accept the general type (
Iterable<num>): any more specific list will work. - If it writes, make it generic (
void addAll<T>(List<T> list, T value)) or return a new collection instead of modifying the argument.
Generic type aliases and function types
typedef can take type parameters too. This is useful for giving names to function types and to long collection types:
typedef Predicate<T> = bool Function(T value);
typedef Json = Map<String, Object?>;
typedef Cache<V> = Map<String, V>;
List<T> where<T>(List<T> items, Predicate<T> test) =>
[for (final i in items) if (test(i)) i];
void main() {
Predicate<String> isLong = (s) => s.length > 3;
print(where(['go', 'dart', 'rust', 'c'], isLong));
print(where([5, 12, 7, 20], (n) => n > 6));
Json user = {'name': 'Ann', 'age': 31};
print(user);
final Cache<int> hits = {};
hits['home'] = 3;
print(hits);
}
Output:
[dart, rust]
[12, 7, 20]
{name: Ann, age: 31}
{home: 3}
A function type like R Function(T) can be used directly as a parameter type, as in mapAll earlier. A typedef is worth it when the same shape appears in several signatures.
Extensions can also be generic. extension<T> on List<T> adds methods to every list while keeping the element type; see Extension methods.
Generic interfaces
Generic abstract classes and interfaces describe contracts that work for many types. A repository is the classic example: the storage logic is the same for users, orders and products, and the bound T extends Entity guarantees every item has an id:
abstract interface class Entity {
int get id;
}
class User implements Entity {
@override
final int id;
final String name;
User(this.id, this.name);
@override
String toString() => 'User($id, $name)';
}
abstract interface class Repository<T extends Entity> {
void save(T item);
T? findById(int id);
List<T> all();
}
class MemoryRepository<T extends Entity> implements Repository<T> {
final _items = <int, T>{};
@override
void save(T item) => _items[item.id] = item;
@override
T? findById(int id) => _items[id];
@override
List<T> all() => _items.values.toList();
}
void main() {
final Repository<User> users = MemoryRepository();
users.save(User(1, 'Ann'));
users.save(User(2, 'Bob'));
print(users.findById(2));
print(users.findById(3));
print(users.all());
}
Output:
User(2, Bob)
null
[User(1, Ann), User(2, Bob)]
MemoryRepository() didn't need <User>: the type argument was inferred from the declared type of the variable it's assigned to. This is called downward inference, and it works for constructors, collection literals and generic function calls alike.
Generic sealed classes
Generics combine well with sealed classes and Pattern matching. A Result<T> type represents either a value of type T or an error, and the compiler checks that every switch handles both cases:
sealed class Result<T> {
const Result();
}
final class Ok<T> extends Result<T> {
final T value;
const Ok(this.value);
}
final class Err<T> extends Result<T> {
final String message;
const Err(this.message);
}
Result<int> parsePort(String s) {
final n = int.tryParse(s);
if (n == null) return Err('not a number: $s');
if (n < 1 || n > 65535) return Err('out of range: $n');
return Ok(n);
}
Result<R> mapResult<T, R>(Result<T> r, R Function(T) f) => switch (r) {
Ok(:final value) => Ok(f(value)),
Err(:final message) => Err(message),
};
void main() {
for (final input in ['8080', 'abc', '70000']) {
final r = mapResult(parsePort(input), (p) => 'http://localhost:$p');
final text = switch (r) {
Ok(:final value) => 'ok: $value',
Err(:final message) => 'error: $message',
};
print(text);
}
}
Output:
ok: http://localhost:8080
error: not a number: abc
error: out of range: 70000
mapResult is a generic function with two type parameters: it turns a Result<int> into a Result<String> without unwrapping it by hand. Inside the switch, the patterns Ok(:final value) know that value has type T.
Generics in async code
Future<T> and Stream<T> are ordinary generic classes, so async helpers become generic just like synchronous ones. A retry helper works for any operation, and its return type follows the type of the operation:
Future<T> retry<T>(Future<T> Function() action, {int attempts = 3}) async {
for (var i = 1;; i++) {
try {
return await action();
} catch (e) {
if (i == attempts) rethrow;
print('attempt $i failed: $e');
}
}
}
var calls = 0;
Future<int> flakyFetch() async {
calls++;
if (calls < 3) throw Exception('timeout');
return 200;
}
Future<void> main() async {
final status = await retry(flakyFetch); // T inferred as int
print('status $status after $calls calls');
final Stream<String> words = Stream.fromIterable(['a', 'bb', 'ccc']);
final List<int> lengths = await words.map((w) => w.length).toList();
print(lengths);
}
Output:
attempt 1 failed: Exception: timeout
attempt 2 failed: Exception: timeout
status 200 after 3 calls
[1, 2, 3]
Because flakyFetch returns Future<int>, retry is inferred as retry<int> and status is an int. See Async and Await for more on futures and streams.
Summary
- Declare type parameters with
<T>after a class, function, method, typedef or extension name. - Let Dart infer type arguments; write them explicitly when inference picks the wrong type or there's nothing to infer from (
<int>[]). - Use
T extends Boundto call members ofBoundon values of typeT.T extends Objectexcludes nullable types. - Type arguments exist at runtime:
is List<int>and'$T'work, butT()doesn't, so pass factories. - Generic classes are covariant: reading is always safe, writing through a supertype view is checked at runtime and can throw
TypeError. - Avoid accidental
dynamic: empty untyped literals and raw types likeListlose type checking.