Explain it simply
Generics and extensions in plain language
A generic is code with a blank left for a type. When you write List<T>, the blank T is filled with int, String or anything else, and each kind of list keeps hold of its type. Instead of writing one function for int and another for String, you write one version with a blank.
An extension lets you add methods to a class you do not own, such as String, List or int. Without touching the source you can write 'dart'.capitalized. Both features do their work at compile time, which keeps your code readable and trustworthy.
Problem → Why → Solution
The problem: one copy per type, or dynamic
You need a function that finds the largest value in a list. After writing it for int, the String list needs one, then a DateTime list, and you end up renaming and copying three functions with identical logic. Reaching for dynamic to avoid that means the compiler checks nothing, so a list that mixes int and String fails only at run time.
A similar pain comes from helpers for types you do not own. capitalize(trim(name)) reads inside-out and never shows up in autocomplete, while name.trim().capitalized reads left to right and is easy to discover.
int largestInt(List<int> items) {
var best = items.first;
for (final item in items) {
if (item > best) best = item;
}
return best;
}
String largestString(List<String> items) {
var best = items.first;
for (final item in items) {
if (item.compareTo(best) > 0) best = item; // same logic, copied again
}
return best;
}
dynamic largestAny(List items) {
var best = items.first;
for (final item in items) {
if (item.compareTo(best) > 0) best = item; // throws if items are mixed
}
return best;
}
String capitalize(String s) => s.isEmpty ? s : s[0].toUpperCase() + s.substring(1);Copying and dynamic both fail
Copying makes one bug a three-place fix, and dynamic discards the type, so the result of largestAny([3, 9]) + 1 is no longer known to the compiler. A generic keeps one piece of logic and fills in T at each call, so an int list returns an int. An extension gives an existing type new methods as if you owned it.
Core concept: type parameters, bounds, extensions and extension types
Type parameters are declared with <T> on functions, classes, typedefs and methods, and at a call Dart infers T from the arguments; Box<int> and Box<String> are different types. Dart generics are reified, so type arguments survive at run time: <int>[] is List<String> is false. A List<int> is also accepted as a List<num> (covariance), but adding a double to that list fails at run time with a TypeError, not at compile time (reproduced).
A bound restricts T and lets the body rely on something. T extends Comparable<T> says 'T can be compared with itself', so compareTo is callable inside. Without the bound, T is only Object?, and you get "The method 'compareTo' isn't defined for the type 'Object?'." Calling the function with a class that is not Comparable fails at the call site too (see the section below).
An extension method, extension Name on Type { ... }, adds methods, getters, setters and operators (but not fields). It is chosen by the receiver's compile-time type, so a dynamic variable never sees it, and the class's own member always wins (an extension cannot replace String's length). It can be generic, extension ListTools<T> on List<T>, or target a nullable receiver, extension on String?.
An extension type (Dart 3.3 and later), written extension type Meters(double value), wraps an existing value in a new compile-time type at zero run-time cost. Meters and Feet are both doubles underneath yet cannot be mixed up at compile time. The wrapper disappears at run time, though, so the protection exists only at compile time.
| Tool | What it solves |
|---|---|
| <T> generic | One implementation for many types |
| T extends X bound | The body may use X's members; callers are restricted |
| Extension method | Helpers on a type you do not own; no fields |
| Extension type | A distinct compile-time type over a value; erased at run time |
- <T> leaves a blank for a type
- extends narrows the blank's options
- Each call fills the blank by inference
- An extension lends methods statically
Extension methods are chosen by the static type, so a dynamic variable never sees them.
General pattern
T name<T extends Bound>(List<T> items) { /* may use Bound's members */ }
class Holder<T> {
Holder(this.value);
final T value;
}
extension Tools on TargetType {
Result get helper => /* uses this */;
}
extension ListTools<T> on List<T> { T? get second => /* ... */; }
extension type Id(int value) { bool get isValid => /* ... */; }A generic function declares <T> after its name and may add a bound with extends. An extension takes the type after on as its receiver and reaches it through this, while an extension type wraps the representation value in parentheses.
Worked example: a generic function, a generic class and two extensions
largest works with any Comparable type (int, String and more). Box<T> holds a value and map turns it into another type, and each map changes Box's type parameter too. NumberStats adds an average getter to Iterable<num>, and StringTools adds capitalized and isBlank to String.
// A bounded generic function: T must be comparable with itself.
T largest<T extends Comparable<T>>(List<T> items) {
var best = items.first;
for (final item in items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
// A generic class: Box<int> and Box<String> are different types.
class Box<T> {
Box(this.value);
final T value;
Box<R> map<R>(R Function(T value) transform) => Box(transform(value));
@override
String toString() => 'Box($value)';
}
// Extensions add methods to types you do not own.
extension NumberStats on Iterable<num> {
double get average => isEmpty ? 0 : fold<num>(0, (a, b) => a + b) / length;
}
extension StringTools on String {
String get capitalized =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
bool get isBlank => trim().isEmpty;
}
void main() {
print(largest([3, 9, 4]));
print(largest(['pear', 'apple', 'zebra']));
final box = Box(21).map((n) => n * 2).map((n) => 'answer $n');
print(box);
print([2, 4, 9].average);
print('dart'.capitalized);
print(' '.isBlank);
}Code breakdown
- Bounded generic function
T largest<T extends Comparable<T>>(List<T> items) {Because of T extends Comparable<T>, the body can compare two T values with compareTo. The return type is also T, so an int list returns an int.
- Use the bound
if (item.compareTo(best) > 0) best = item;Without the bound this line would not compile, because Object? has no compareTo. A positive result means item is greater than best.
- Generic class method
Box<R> map<R>(R Function(T value) transform) => Box(transform(value));A method can have its own type parameter, R. Mapping a Box<int> to a String yields a Box<String>, so you can chain calls and change the type step by step.
- Extension on a generic type
extension NumberStats on Iterable<num> {on Iterable<num> means average is available on every collection of numbers, such as List<int> or Set<double>, because List<int> is a subtype of Iterable<num>.
- Extension getter
bool get isBlank => trim().isEmpty;Inside an extension, calling trim() without this means the receiver String's trim. At the call site it reads like an ordinary member: ' '.isBlank.
- Chained inference
final box = Box(21).map((n) => n * 2).map((n) => 'answer $n');Box(21) is a Box<int>, the first map gives a Box<int>, and the second gives a Box<String>, all without one type annotation. Printing it gives Box(answer 42).
9
zebra
Box(answer 42)
5.0
Dart
trueBounds and variance: where generic code surprises people
With a bound such as T extends num, int and double are accepted and String is refused. Pass a Version class that is not Comparable to largest and the compiler rejects the call itself with "Inferred type argument 'Comparable<Object?>' doesn't conform to the bound 'Comparable<T>' of the type variable 'T' on 'largest'." (reproduced). The code below shows a bound, reified types and covariance together.
num total<T extends num>(List<T> xs) => xs.fold<num>(0, (a, b) => a + b);
void main() {
print(total([1, 2, 3])); // 6
print(total([1.5, 2.5])); // 4.0
print(<int>[] is List<String>); // false: type arguments exist at run time
List<num> nums = <int>[1, 2]; // allowed: List<int> is a List<num>
print(nums is List<int>); // true: the real list is still a List<int>
try {
nums.add(1.5); // unsafe write: checked at run time, not compile time
} on TypeError catch (e) {
print(e);
}
}The last line prints "type 'double' is not a subtype of type 'int' of 'value'" (reproduced on 3.13.7; the wording can differ between versions). So when you receive a list declared with a supertype like List<num>, do not assume you may add anything to it: the real list's type has the last word.
The rules of extension methods
The code below has three extension pieces: shout on String, an attempt to add its own length (the class's length wins), and orDash on String?. A dynamic receiver does not see extensions, yet you can apply one explicitly with Shout('hey').shout.
extension Shout on String {
String get shout => '${toUpperCase()}!';
int get length => 99; // the class's own length wins; this is never used
}
extension on String? {
String get orDash => this ?? '-';
}
void main() {
print('hi'.shout);
print('hi'.length);
String? missing;
print(missing.orDash);
dynamic d = 'hi';
try {
print(d.shout);
} on NoSuchMethodError {
print('dynamic receiver cannot see extensions');
}
print(Shout('hey').shout); // explicit application
}HI!
2
-
dynamic receiver cannot see extensions
HEY!If two extensions declare the same name, tag, on int, then 5.tag fails with "The property 'tag' is defined in multiple extensions for 'int' and neither is more specific." (reproduced). There are two fixes: apply one explicitly, A(5).tag, or use hide/show on the import. Declaring a field inside an extension gives "Extensions can't declare instance fields"; a static field is allowed.
extension A on int {
String get tag => 'A';
}
extension B on int {
String get tag => 'B';
}
void main() {
// print(5.tag); // error: defined in multiple extensions for 'int'
print(A(5).tag); // A
print(B(5).tag); // B
}Extension types (Dart 3.3 and later)
An extension type turns an existing type (the representation type) into a new compile-time type. It suits values that are an int or double underneath but must not be mixed up, such as IDs (UserId versus OrderId) and units (Meters versus Feet). Only the members you declare, plus anything you implement, can be called.
extension type const Meters(double value) {
Meters operator +(Meters other) => Meters(value + other.value);
String describe() => '$value m';
}
extension type const Feet(double value) {
Meters toMeters() => Meters(value * 0.3048);
}
extension type UserId(int id) {
bool get isValid => id > 0;
}
String report(Meters distance) => 'distance: ${distance.describe()}';
void main() {
final a = Meters(3);
final b = Meters(2.5);
print(report(a + b));
print(report(Feet(10).toMeters()));
print(UserId(7).isValid);
dynamic erased = a;
print(erased is double); // true: the wrapper is gone at run time
print(erased.runtimeType); // double
}distance: 5.5 m
distance: 3.048 m
true
true
doublereport(Feet(1)) gives the compile error "The argument type 'Feet' can't be assigned to the parameter type 'Meters'.", yet at run time both are plain doubles, so passing one through a dynamic slips past that protection (reproduced). Meters m = 3.0; does not compile, and m.toStringAsFixed(1) is unavailable unless you add implements double. The feature needs language version 3.3: running with // @dart=3.2 reports "The 'inline-class' language feature is disabled for this library." and "setting the language version to 3.3 or higher" (inline-class is the feature's internal name).
In real projects
Where generics and extensions show up in real projects
Dart's whole standard library is built on generics: List<E>, Map<K, V>, Future<T>, Stream<T>, Iterable<E>. Flutter has bounds such as State<T extends StatefulWidget>. Writing your own generics pays off most in layers that handle many data types, such as repositories, caches and result wrappers.
- Extensions in dart:core: firstOrNull and nonNulls come as extensions on Iterable, so do not rewrite them; check what already exists first.
- Apps commonly write extensions for DateTime, String and BuildContext (for example date.formatted or context.theme), and keeping these helpers in one xxx_extensions.dart file makes them easy to find.
- Extension types for IDs and units: UserId and OrderId are both ints, yet a function signature can no longer mix them up, and because no wrapper object exists at run time there is no performance cost.
void main() {
final empty = <int>[];
print(empty.firstOrNull); // null, from an extension in dart:core
print([4, 8].firstOrNull); // 4
final names = ['mia', null, 'joe'];
print(names.nonNulls.toList()); // [mia, joe]
}Common mistakes
Common mistakes with generics and extensions
Leaving a collection untyped and getting dynamic
var loose = []; has no type argument, so it is a List<dynamic> (its runtimeType prints List<dynamic>) and the compiler stops checking its elements. Give it a type: <String>[] or List<String> loose = [].
Calling a method on T without a bound
Inside T largest<T>(List<T> items), writing item.compareTo(best) gives "The method 'compareTo' isn't defined for the type 'Object?'." (reproduced). Add the bound T extends Comparable<T> instead of patching it with (item as dynamic).compareTo.
Expecting an extension to override a member or reach a dynamic receiver
int get length => 99; in a String extension does not change 'hi'.length (it still gives 2), and dynamic d = 'hi'; d.shout throws NoSuchMethodError. Extensions work on the static type and the class's own member wins on a name clash, so choose a new name.
Treating an extension type as a run-time boundary
Put Meters(3) in a dynamic and an is double check returns true, because the wrapper does not exist at run time. So do not assume that casting outside data such as JSON to Meters validated it; check the value in a constructor.
Best practices
Best practices
- Follow the naming habits: T for a type, E for an element, K and V for key and value, and role names when there are several.
- Let inference do the work; write explicit arguments such as <int>[] only where nothing can be inferred.
- Use the loosest bound the body really needs so callers stay free.
- Choose extensions for types you do not own, and write members on your own classes. Give each extension a clear name, because it appears in conflict errors.
Mini challenge
Mini challenge: Pair, clamp and chunked
Write three generic pieces: a Pair<A, B> class that holds two types (swap() returns a Pair<B, A>), a clamp function for any Comparable type, and an extension on List that adds chunked(size). Then print the results.
- Pair<A, B> has final fields first and second, and swap() returns a Pair<B, A>
- clamp<T extends Comparable<T>>(T value, T low, T high) returns the value limited to the range low..high
- A ListChunks<T> extension makes [1, 2, 3, 4, 5].chunked(2) return [[1, 2], [3, 4], [5]]
- Call clamp with both ints and Strings and print every result
// TODO 1: make Pair generic in A and B; add final fields first and second,
// a swap() that returns Pair<B, A>, and a toString like '(1, one)'
class Pair {
// TODO
}
// TODO 2: clamp<T extends Comparable<T>>(T value, T low, T high)
// low if value < low, high if value > high, otherwise value
// TODO 3: extension ListChunks<T> on List<T> with chunked(int size)
// returning List<List<T>>; use sublist and mind the last short chunk
void main() {
// TODO 4: print Pair(1, 'one').swap(), clamp(15, 0, 10), clamp('m', 'a', 'f')
// and [1, 2, 3, 4, 5].chunked(2)
}Expected: Running it should print: (one, 1) 10 f [[1, 2], [3, 4], [5]]
Show hint
For Pair, write Pair<B, A> swap() => Pair(second, first);. In clamp, check whether compareTo is below or above 0. In chunked, loop with i increasing by size and use end = min(i + size, length) for the last short chunk.
Show solution
class Pair<A, B> {
Pair(this.first, this.second);
final A first;
final B second;
Pair<B, A> swap() => Pair(second, first);
@override
String toString() => '($first, $second)';
}
T clamp<T extends Comparable<T>>(T value, T low, T high) {
if (value.compareTo(low) < 0) return low;
if (value.compareTo(high) > 0) return high;
return value;
}
extension ListChunks<T> on List<T> {
List<List<T>> chunked(int size) {
final result = <List<T>>[];
for (var i = 0; i < length; i += size) {
final end = i + size > length ? length : i + size;
result.add(sublist(i, end));
}
return result;
}
}
void main() {
print(Pair(1, 'one').swap());
print(clamp(15, 0, 10));
print(clamp('m', 'a', 'f'));
print([1, 2, 3, 4, 5].chunked(2));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A type parameter <T> lets one piece of code serve many types, and Dart generics survive at run time: a List<int> is accepted as a List<num>, but an unsafe write is caught at run time.
- A bound (T extends Comparable<T>) lets the body use T's members and rejects mismatched types at the call site.
- Extension methods are chosen by static type and cannot add fields; the class's own member always wins and a dynamic receiver cannot see them.
- An extension type (Dart 3.3+) is a distinct type at compile time, but the wrapper is gone at run time, so do not rely on it for validation.
Dart language overview — Dart