Dart Generics

Dart Generics are the same as the Dart collections, which are used to store the homogenous data. As we discussed in the Dart features, it is an optionally typed language.

By default, Dart Collections are the heterogeneous type. In other words, a single Dart collection can hold the values of several data types. However, a Dart collection can be also stored the homogenous values or same type values.

The Dart Generics provides the facility to enforce a limit on the data type of the values that can be stored by the collection. These collections can be referred to as the type-safe collections.

Type safety is a unique feature of the Dart programming, which makes sure that a memory block can only contain the data of a specific data type.

The generics are a way to support type-safety implementation for all Dart collections. The pair of the angular bracket is used to declare the type-safe collection. The angular bracket consists of the data-types of the collection. The syntax is given below.

Syntax -

We can do the type-safe implementation of various Dart objects such as List, Queue, Map, and Set. It is also supported by all implementation of the above define collection types. The syntax is given below.

Example - Generics List

Output

CHECK
ERROR
INFO

Explanation:

We created a list that holds the string type-safe and used the add element into it by using add() function.

If we try to insert the other than the specified value then it will through a compilation error. Let's understand the following example -

Example - 2

Output

generics.dart:3:17: Error: The argument type 'int' can't be assigned to the parameter type 'String'.
logTypes.add(511);

Let's understand another example -

Example - Generic Set

Output

10
20
30
40
50

Example - Generics Queue

Output

Default implementation ListQueue<int>
205
315
470

Generic Map

As we know that declaring map require the key and value. The syntax is given below.

Syntax:

Example -

Output

Map :{name: Joseph, Rollno: Std1001}

Next TopicDart Packages




Latest Courses