Generics trong Dart
🎯 Mục tiêu: Type-safe code với generics.
💡 Generic Class
class Box<T> {
T value;
Box(this.value);
}
var intBox = Box<int>(42);
var stringBox = Box<String>("Hello");📝 Generic Function
T first<T>(List<T> items) => items.first;
var number = first<int>([1, 2, 3]); // Type inference
var word = first(['a', 'b', 'c']);🔧 Constraints
class SortedList<T extends Comparable<T>> {
final List<T> _items = [];
void add(T item) {
_items.add(item);
_items.sort();
}
}✅ Checklist
-
<T>cho type parameter -
extendscho constraints - Collections là generic:
List<T>,Map<K, V>
Last updated on