Generics in Dart — Part I
Intro to generics in Dart.

We will discuss the below topics in two parts:
- Intro to Generics for creating generic classes and functions.
- How does it fit in the Dart type system (you can read it as Subtyping in Dart if you are coming from the Java world)?
In this, we will solely focus on 1.
Generics are often used for primarily two purposes:
- To reduce code duplication.
- Better generated code.
How to create a Generic class?
Let us suppose there are no generics in Dart and you need to create an interface for a cache which simply stores a value for a key. Either you will use dynamic or spend all day creating abstract classes for different types e.g ObjectCache & StringCache.
Now let’s see how we will use generics here. The annotation <..> marks a class as a generic type. By convention, most type variables have single-letter names such as E, K & T etc.
Replacing concrete type with type variable T we are able to create a Cache class via which we can create Cache for any type without rewriting the interface again and again for different types. Below is an example of how you create StringCache which extends the generic Cache interface.
Similarly we can implement concrete generic class, lets take example of Stack.
How to create generic methods?
Earlier Dart used to support only class generics but now it supports generic methods as well. Below is one example:
Restricting the parameterized type
Sometimes you might want to restrict the type user of your generic type can provide.
A common use case is to prevent nullable type from being passed as a type parameter by making it a subtype of Object. Here are a few examples: