...

/

Declaring Type-Safe Collections

Declaring Type-Safe Collections

Learn about declaring type-safe collections using generics.

Declaring Type-Safe Collections

In the previous lesson, you learned that Dart allows for storing different types of data in one collection. But a problem could arise if Dart is unable to handle all types of data in a given collection.

In this lesson, you will learn to declare type-safe collections to solve this problem.

To ensure type safety, the angular brackets <> with data type enclosed, are used to declare the collection of the given data type. Type safety ensures that only one type of data can be stored in one collection.

Syntax:

CollectionType <dataType> identifier = CollectionType <dataType>();

Example:

List<int> numbers = List<int>();

Generics are parameterized. They use type variable notations to restrict the type of data.

We can understand this with the help of an example. Assume that you have three classes:

  • Product Class: This class represents a grocery item. It has id, title, and price members to define a product.
//A class for grocery product
class Product {
  final int id;
  final
...