Dart Generics
Generics let you write code without specifying a concrete type, using a type parameter as a placeholder and determining the type when it is used.
The core value of generics is type safety and code reuse -- one piece of code works with many types while the compiler checks type errors for you.
Why Do We Need Generics
First, let's look at the pain points without generics.
Example
Writing it without generics:
// Without generics: can only hold Object, and you must manually cast when retrieving
class
IntBox
{
int
value
;
IntBox
(
this
.
value
)
;
}
class
StringBox
{
String value
;
StringBox
(
this
.
value
)
;
}
// Every new type requires writing a new Box class, causing a lot of duplicated code
void
main
(
)
{
var
intBox
=
IntBox
(
42
)
;
var
stringBox
=
StringBox
(
'RUNOOB'
)
;
(
'Integer: ${intBox.value}'
)
;
(
'String: ${stringBox.value}'
)
;
}
Is there a way to write a Box class that can hold both int and String while still guaranteeing type safety at compile time?
This is exactly the problem generics solve.
Generic class
A generic class uses angle brackets after the class name <> to declare type parameters, and the class uses this type parameter internally.
Example
//
// Conventional names: T (Type), E (Element), K (Key), V (Value)
class
Box
<
T
{T value
;
Box
(
this
.
value
)
;
T getValue
(
)
{
return
value
;
}
void
setValue
(
T newValue
)
{
value
=
newValue
;
}
void
printValue
(
)
{
(
'Value in Box: $value (type: ${value.runtimeType})'
)
;
}
}
void
main
(
)
{
// Specify a concrete type when using a generic class
var
intBox
=
Box
<
int
(
42
);
var
stringBox
=
Box
<
String
('RUNOOB Dart Tutorial'
)
;
var
doubleBox
=
Box
<
double
(
3.14
);
intBox.
printValue
(
)
;
stringBox.
printValue
(
)
;
doubleBox.
printValue
(
)
;
// Type safety: the following code will produce a compile-time error
// intBox.setValue('hello'); // Error: String cannot be assigned to int
// Type inference: Dart can infer the type from constructor arguments
var
autoBox
=
Box
(
'Automatically inferred as String'
)
;
(
'Inferred type: ${autoBox.value.runtimeType}'
)
;
}
Box 中的值: 42 (类型: int)
Box 中的值: RUNOOB Dart 教程 (类型: String)
Box 中的值: 3.14 (类型: double)
推断类型: String
Multiple Type Parameters
A generic class can have multiple type parameters.
Example
// K represents the key type, V represents the value type
class
Pair
<
K
,
V
{K key
;
V value
;
Pair
(
this
.
key
,
this
.
value
)
;
@override
String toString
(
)
=>
'Pair($key: $value)'
;
}
void
main
(
)
{
var
pair1
=
Pair
<
String
,
int
(
'runoob'
,
10
);
var
pair2
=
Pair
(
'score'
,
95.5
)
;
// Type inference
(
pair1
)
;
(
pair2
)
;
}
Pair(runoob: 10)
Pair(score: 95.5)
Generic method
Besides generic classes, functions and methods can also use generics.
Example
// Generic function: the return type matches the parameter type
// Declared before the return type
T firstElement
<
T
(
List
<
T
list
)
{
if
(list.
isEmpty
)
{
throw
ArgumentError
(
'The list cannot be empty'
)
;
}
return
list
[
0
]
;
}
// Generic function: swap two values
void
swap
<
T
(
List
<
T
list
,
int
i
,
int
j
)
{T temp
=
list
[
i
]
;
list
[
i
]
=
list
[
j
]
;
list
[
j
]
=
temp
;
}
void
main
(
)
{
// Dart automatically infers the type at the call site
var
names
=
[
'runoob'
,
'Dart'
,
'Flutter'
]
;
(
'First name: ${firstElement(names)}'
)
;
var
scores
=
[
95
,
88
,
72
]
;
(
'First score: ${firstElement(scores)}'
)
;
// Swap the elements
var
items
=
[
'A'
,
'B'
,
'C'
]
;
(
'Before swap: $items'
)
;
swap
(
items
,
0
,
2
)
;
(
'After swap: $items'
)
;
}
第一个名字: runoob
第一个分数: 95
交换前: [A, B, C]
交换后: [C, B, A]
Type Constraints with extends
Sometimes you want a type parameter to be restricted to subtypes of a certain type.
Use the extends keyword to place constraints on generic parameters.
Example
// Define a numeric calculator
//
class
Calculator
<
T
extends
num
{T a
;
T b
;
Calculator
(
this
.
a
,
this
.
b
)
;
// Because T extends num is constrained, num methods can be used safely
double
add
(
)
=>
(
a
b
)
.
toDouble
(
)
;
double
subtract
(
)
=>
(
a
b
)
.
toDouble
(
)
;
double
multiply
(
)
=>
(
a
b
)
.
toDouble
(
)
;
double
divide
(
)
=>
a
/
b
;
void
printOperations
(
)
{
(
'RUNOOB Calculator: $a and $b'
)
;
(
' Add: ${add()}'
)
;
(
' Subtract: ${subtract()}'
)
;
(
' Multiply: ${multiply()}'
)
;
(
' Divide: ${divide().toStringAsFixed(2)}'
)
;
}
}
void
main
(
)
{
var
intCalc
=
Calculator
<
int
(
10
,
3
);
intCalc.
printOperations
(
)
;
var
doubleCalc
=
Calculator
<
double
(
3.5
,
1.5
);
doubleCalc.
printOperations
(
)
;
// The following line will error: String is not a subtype of num
// var strCalc = Calculator
}
RUNOOB 计算器: 10 和 3
加: 13.0
减: 7.0
乘: 30.0
除: 3.33
RUNOOB 计算器: 3.5 和 1.5
加: 5.0
减: 2.0
乘: 5.25
除: 2.33
Type constraints let you keep the flexibility of generics while still using methods of the constrained type. For example, by constraining T extends num above, you can use operators such as +, -, *, / inside the method body because the num type supports these operations.
Using Generic Collections
Dart's core collection classes (List, Set, Map) are all generic.
Using generic collections gives you compile-time type checking.
Example
void
main
(
)
{
// Specify the element type as String
List
<
String
names
=
[
'runoob'
,
'Dart'
,
'Flutter'
];
// names.add(42); // Error: int cannot be added to a List
// Specify the key and value types
Map
<
String
,
int
scores
=
{
'runoob':
95
,
'Alice'
:
87
,
}
;
// scores['Bob'] = 'Excellent'; // Error: String cannot be assigned to int
// Specify the Set element type
Set
<
double
prices
=
{
9.99
,
19.99
,
29.99
};
// Functional operations on generic collections
List
<
int
numbers
=
[
1
,
2
,
3
,
4
,
5
,
6
];
// Type-safe filtering and mapping
List
<
int
evenNumbers
=numbers.
where
(
(
n
)
=>
n
%
2
==
0
)
.
toList
(
)
;
List
<
String
labels
=numbers.
map
(
(
n
)
=>
'RUNOOB-$n'
)
.
toList
(
)
;
(
'Even numbers: $evenNumbers'
)
;
(
'Labels: $labels'
)
;
// Use fold for type-safe cumulative computation
int
sum
=
numbers.
fold
<
int
(
0
,
(
prev
,
n
)
=>
prev
n
);
(
'Total: $sum'
)
;
}
偶数: [2, 4, 6]
标签: [RUNOOB-1, RUNOOB-2, RUNOOB-3, RUNOOB-4, RUNOOB-5, RUNOOB-6]
总和: 21
Practical Application: The Generic Repository Pattern
One of the most classic uses of generics in real development is the "Repository Pattern".
Example
// Define a generic repository interface
abstract
class
Repository
<
T
{
void
add
(T item
)
;
void
remove
(
T item
)
;
T
?
findById
(
String id
)
;
List
<
T
getAll
(
);
}
// User model
class
User
{
String id
;
String name
;
User
(
this
.
id
,
this
.
name
)
;
@override
String toString
(
)
=>
'User($id, $name)'
;
}
// Product model
class
Product
{
String id
;
String name
;
double
price
;
Product
(
this
.
id
,
this
.
name
,
this
.
price
)
;
@override
String toString
(
)
=>
'Product($name, ¥$price)'
;
}
// Concrete implementation: user repository
class
UserRepository
implements
Repository
<
User
{
final
List
<
User
_users
=
[
];
@override
void
add
(
User user
)
=>
_users.
add
(
user
)
;
@override
void
remove
(
User user
)
=>
_users.
remove
(
user
)
;
@override
User
?
findById
(
String id
)
{
try
{
return
_users.
firstWhere
(
(
u
)
=>
u.
id
==
id
)
;
}
catch
(
_
)
{
return
null
;
}
}
@override
List
<
User
getAll
(
)
=>List.
unmodifiable
(
_users
)
;
}
// Concrete implementation: product repository (same interface, different type)
class
ProductRepository
implements
Repository
<
Product
{
final
List
<
Product
_products
=
[
];
@override
void
add
(
Product product
)
=>
_products.
add
(
product
)
;
@override
void
remove
(
Product product
)
=>
_products.
remove
(
product
)
;
@override
Product
?
findById
(
String id
)
{
try
{
return
_products.
firstWhere
(
(
p
)
=>
p.
id
==
id
)
;
}
catch
(
_
)
{
return
null
;
}
}
@override
List
<
Product
getAll
(
)
=>List.
unmodifiable
(
_products
)
;
}
void
main
(
)
{
var
userRepo
=
UserRepository
(
)
;
userRepo.
add
(
User
(
'u1'
,
'runoob'
)
)
;
userRepo.
add
(
User
(
'u2'
,
'Alice'
)
)
;
var
productRepo
=
ProductRepository
(
)
;
productRepo.
add
(
Product
(
'p1'
,
'Dart Tutorial'
,
29.99
)
)
;
productRepo.
add
(
Product
(
'p2'
,
'Flutter Tutorial'
,
49.99
)
)
;
(
'User list: ${userRepo.getAll()}'
)
;
(
'Product list: ${productRepo.getAll()}'
)
;
(
'Find user u1: ${userRepo.findById('
u1
')}'
)
;
(
'Find product p2: ${productRepo.findById('
p2
')}'
)
;
}
用户列表: [User(u1, runoob), User(u2, Alice)]
商品列表: [Product(Dart 教程, ¥29.99), Product(Flutter 教程, ¥49.99)]
查找用户 u1: User(u1, runoob)
查找商品 p2: Product(Flutter 教程, ¥49.99)
The generic repository pattern lets you handle different types of data through a unified interface, ensuring type safety while avoiding duplicated code.