Dart Generics : Creating Generic Classes

Dart Generics : Creating Generic Classes

·

1 min read

Creating Generic Classes

  • Generics is a way to create a class, or function that can work with different types of data (objects). If you look at the internal implementation of List class, it is a generic class.

Syntax :

class ClassName<T> {
  // code
}
// Using Generics
class Data<T> {
  T data;
  Data(this.data);
}

void main() {
  // create an object of type int and double
  Data<int> intData = Data<int>(10);
  Data<double> doubleData = Data<double>(10.5);
  Data<String> stringData = Data<String>("Hello");

  // print the data
  print("IntData: ${intData.data}");
  print("DoubleData: ${doubleData.data}");
  print('StingType : ${stringData.data}');
}