Sobes.tech
Junior — Middle

Explain the concept of Generics in the Dart language and how it helps in writing flexible code.

sobes.tech AI

Answer from AI

Generics in Dart allow creating classes, methods, and functions that work with different data types while maintaining type safety. This means you can write more flexible and reusable code without sacrificing compile-time type checking.

For example, instead of creating separate lists for each data type, you can use a generic List<T>, where T is a type parameter. This helps avoid errors related to incorrect data types and improves code readability.

Example:

class Box<T> {
  T content;
  Box(this.content);

  void showContent() {
    print('Content: $content');
  }
}

void main() {
  var intBox = Box<int>(123);
  intBox.showContent(); // Content: 123

  var stringBox = Box<String>('Hello');
  stringBox.showContent(); // Content: Hello
}

Thus, Generics help write flexible, safe, and maintainable code.