Skip to content
Dart

Generics

Type-safe reusable classes and methods.

By EZ4Code Team
generictype-safe

Code

class Stack<T> {
  final List<T> _items = [];

  void push(T item) => _items.add(item);
  T pop() => _items.removeLast();
  bool get isEmpty => _items.isEmpty;
}

// Generic method
T firstOrDefault<T>(List<T> list, T defaultValue) {
  return list.isEmpty ? defaultValue : list.first;
}

// Bounded generics
class Repository<T extends Entity> {
  final List<T> items = [];
  void add(T item) => items.add(item);
  T findById(int id) => items.firstWhere((i) => i.id == id);
}

abstract class Entity {
  int get id;
}

// Generic typedef
typedef Mapper<T, R> = R Function(T);

// Usage
void main() {
  var stack = Stack<int>();
  stack.push(1);
  stack.push(2);
  print(stack.pop());  // 2

  var names = ['Alice', 'Bob'];
  print(firstOrDefault(names, 'Unknown'));
}

Explanation

Dart generics are reified (type info available at runtime), unlike Java's erasure. extends bounds the type (T must be Entity or subclass). Use generics for collections, repositories, and utility functions. typedef creates type aliases (including generics). Generic methods don't need class-level declaration — T can be declared on the method itself.

More Dart Snippets