Back to results for “Generics”
Flutter › Dart Collections & Generics

How do you create a custom generic class in Dart, and why would a generic class be preferable to writing several nearly identical, separate classes each hardcoded for a different specific type?

Intermediate

Answer

A custom generic class lets you define a reusable class structure once, parameterized with a placeholder type that gets specified later whenever that class is actually used, such as building a generic Result class capable of representing either a successful value of any type or a failure error, and this avoids the need to write and separately maintain several nearly identical classes, each hardcoded for one specific different data type, since the exact same single generic class definition can correctly and safely work with many different concrete types.
class Result<T> {
  final T? value;
  final String? error;
  Result.success(this.value) : error = null;
  Result.failure(this.error) : value = null;
}

final userResult = Result<User>.success(fetchedUser);
Real-world example A networking layer defines a single generic Result class capable of representing either a successful response or a failure for any type of data being fetched, avoiding the need to write a separate, nearly duplicate result class for users, orders, and every other different type of data the app fetches.

Common follow-ups: How do you add a constraint restricting a generic type parameter to only certain kinds of types?;What is the difference between a generic class and a generic function in Dart?