Generics in Dart provide a way to create reusable components that can work with different types while maintaining type safety. They allow you to define classes, functions, and interfaces that can operate on a variety of data types without sacrificing type checking at compile time. Generics are especially useful for writing code that is more flexible, reusable, and maintainable.
class Box
T value;
Box(this.value);
T getValue() => value;
}
var integerBox = Box
var stringBox = Box
T getLast
if (list.isNotEmpty) {
return list.last;
} else {
throw Exception('List is empty');
}
}
var lastNumber = getLast
var lastName = getLast
abstract class Repository
Future
Future
}
class UserRepository implements Repository
@override
Future
// Implementation
}
@override
Future
// Implementation
}
}
var integerBox = Box(10); // Type inference infers < int >
var lastNumber = getLast([1, 2, 3, 4, 5]); // Type inference infers < int >