Advertisement
Advanced Flutter, Dart Collections & Generics

How do bounded type parameters, using the extends keyword within a generic class definition, let you constrain a generic type to only accept types that satisfy a specific requirement?

Short answer

A bounded type parameter lets you restrict a generic class or function so that its type parameter must extend, meaning inherit from or implement, a specific class or interface, which lets you safely call methods defined on that required bound directly within your generic code…

Save Flutter mock interview
Advertisement
AModel answer
A bounded type parameter lets you restrict a generic class or function so that its type parameter must extend, meaning inherit from or implement, a specific class or interface, which lets you safely call methods defined on that required bound directly within your generic code, something that would not otherwise be possible with a completely unconstrained generic type parameter, since Dart cannot know in advance what methods an entirely arbitrary, unconstrained type might actually support.
class Repository<T extends Identifiable> {
  T findById(String id, List<T> items) {
    return items.firstWhere((item) => item.id == id);
  }
}
Real-world example
A generic Repository class constrains its type parameter to only accept types that implement an Identifiable interface, allowing it to safely call the id property directly within its own generic findById method, which would not be possible if the type parameter were left completely unconstrained.
Likely follow-ups
  • What happens if you try to pass a type that does not satisfy the required bound?
  • Can a generic type parameter have more than one bound at the same time?
Related topics