Generics Use generics to parameterize types

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

What are Generics?

Generics are a way to parameterize types. They allow a class to wrap a type, and then use that type in multiple places. For example, we can have a Box class that wraps an double or String type.

file_type_dartlang generics.dart
Box<String> box1 = Box('cool');
Box<double> box2 = Box(2.23);

Using Generics in a Class

A generic type is a type that can be used as a substitute for a type parameter.

file_type_dartlang generics.dart
class Box<T> {
  T value;

  Box(this.value);

  T openBox() {
    return value;
  }
}

Q&A Chat