TExcelTAD
Home › Dart › Dart Generics

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:

dart · try it yourself
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

dart · try it yourself
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:

dart · try it yourself
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:

dart · try it yourself
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:

dart · try it yourself
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 List without arguments — they become List<dynamic> and silently disable type checks.

Test yourself

What does <T extends num> mean?

  1. T must be exactly num
  2. T must be num or a subtype like int or double
  3. T can be any type
  4. T is nullable

Does <String>['a'] is List<int> evaluate to true?

  1. Yes, generics are erased
  2. No — Dart generics are reified, so it's false
  3. Compile error
  4. Throws at runtime

What is the type of Box(3.5) given class Box<T> { T value; Box(this.value); }?

  1. Box<dynamic>
  2. Box<num>
  3. Box<double>
  4. Box<Object>