How do generics work in Dart and why are they important?
TL;DR: Generics let you write type-safe, reusable code. List<T> works for any type while catching mismatches at compile time. Dart generics are reified — type information is preserved at runtime, unlike Java's type erasure.
Full Answer
Dart generics are fully reified — unlike Java, the type T is available at runtime. This means you can check (list is List<String>) and get accurate runtimeType output.
Bounded Generics
Use 'extends' to constrain the type parameter: <T extends Comparable<T>> ensures T has a compareTo method. This is how Flutter's sorted lists and priority queues work.
Generic Methods
Methods can have their own type parameters independently of the class. This lets you write utilities like transform<T, R>(T input, R Function(T) mapper).
Dart's Result<T, E> pattern uses generics: Result<User, AppError> makes success and failure types explicit — no more unchecked exceptions.
Code Examples
7 zoo true false
Common Mistakes
- ✗Using dynamic instead of generics — loses type safety and IDE support
- ✗Forgetting that List<Object> is not a List<String> in Dart — covariance rules apply
Interview Tip
Mention that Dart generics are reified (runtime type info preserved). This differentiates Dart from Java and shows deep language knowledge.