Flutter › Dart Collections & Generics
What are generics in Dart, and how does declaring a collection like List<String> let the Dart compiler catch type related mistakes before your code even runs?
BeginnerAnswer
Generics let you parameterize a class or a collection type with a specific type, such as declaring a List specifically intended to hold only String values as List<String>, and this lets the Dart compiler verify at compile time that only values of that exact expected type are ever actually added to that collection, immediately catching an accidental mistake, such as trying to add an integer to a list that was explicitly declared to hold only strings, well before that mistake could ever cause a genuine runtime error somewhere later in your actual running application.
List<String> names = ['Alex', 'Sarah'];
names.add(42); // Compile time error: an int cannot be assigned to a String listReal-world example A developer accidentally attempts to add a numeric user ID directly into a list explicitly typed as List<String> intended for names, and the Dart compiler immediately catches this specific type mismatch mistake before the app is even run.