Using generics
The <>
syntax is used to specify the type supported by a class. If you look at the examples of lists and maps in Chapter 2, An Introduction to Dart, you will notice that we didn’t specify the type that they can contain. This is because this type of information is optional, and Dart can infer the type based on elements during the collection initialization process.
When and why to use generics
The use of generics can help a developer maintain and keep collection behavior under control. When we use a collection without specifying the allowed element types, it is our responsibility to correctly insert elements of the expected type. This can lead to bugs when data of an incorrect type is placed in a collection or incorrect assumptions are made about the contents of a collection.
Consider the following code example, where we have named a List
variable placeNames
. We expect this to be a list of names and nothing else. Unfortunately, without generics, we...