×

Dart Generics

Dart Generics is similar to Dart collections, which are used to store homogeneous data. As we have discussed in Dart's features, it is a language with types being optional.

By default, Dart collections are of a different type. In other words, a single Dart collection can hold values for several types of data. However, the Dart collection can also be retained for the same values or values of the same type.

Dart Generics provides a data enforcement tool for the type of data that can be stored by the collection. These collections can be called type-safe collections.Type safety is a unique feature of the Dart programming, which ensures that the memory block can only contain data for a specific type of data.

Generations are a way to support type - safety implementation in all Dart collections. A pair of angular brackets is used to declare a type-safe collection. Angular brackets include types of collection data. The syntax to declare or implement generics is as follows :

Syntax -

Collection_name < data_type > identifier = new Collection_name < data_type > 

We can make safe use of a variety of Dart items such as list, queue, map, and Set. It is also supported by all the uses of the above define collection types. Let us consider the following example where we create a generic list.

Example - Generics List

// creating a generic list
void main( ) {   
   // declaring a new generic list
   List < String > list_Str = new List < String >( ) ;   
   // adding the items of type String to the list
   list_Str.add( " This " ) ;   
   list_Str.add( " is " ) ;   
   list_Str.add( " a " ) ;   
   list_Str.add( " String " ) ;   
    
   // Iterating over the list to print the items of the Generic List
   for ( String i in list_Str ) {   
      print( i ) ;   
   }   
}

Output :

This 
is 
a 
String

Explanation :

We created a list containing the string type-safe and used the add element  feature using the add( ) function.

If we try to add a value other than the value of a specified it will happen with a merge error. Let's understand the following example -

Example - 2

void main( ) {   
   // declaring a generic list
   List < String > list_Str = new List < String >( ) ;   
   // adding an integer value in the list
   list_Str.add( 120 ) ;   
   // adding a String value in the list
   list_Str.add( " Generic " ) ;   
   list_Str.add( " List " ) ;   
   // Iterating over the list to print the items of the Generic List   
   for ( String i in logTypes ) {   
      print( i ) ;   
   }   
}  

Output :

generics.dart : 3:17 : Error : The argument type ' int ' can't be assigned to the parameter type ' String '.
list_Str.add( 120 ) ;
Let's understand another example -

Example - Generic Set

Let us consider the following example that depicts generic Set :

void main( ) {   
   // declaring a generic set
   Set < int > num_list = new Set < int >( ) ;   
   // adding integer values in the set
   num_set.add( 1 ) ;   
   num_set.add( 2 ) ;   
   num_set.add( 3 ) ;   
   num_set.add( 4 ) ;  
   num_set.add( 5 ) ;   
   for( var i in num_set ) {   
      print( i ) ;   
   }   
}

Output :

1
2
3
4
5

Example - Generics Queue

Let us consider the following example that depicts generic queue :

import ' dart : collection ' ;   
void main( ) {   
    // declaring a generic queue
   Queue< int > queue = new Queue < int > ( ) ;   
   print( " Default implementation of ${ queue.runtimeType } " ) ;    
   // adding the integer values in the queue at the rear end
   queue.addLast( 5 ) ;   
   queue.addLast( 1 ) ;   
   queue.addLast( 2 ) ;   
   queue.addLast( 0 ) ;   
   queue.addLast( 2 ) ;   
   // removing the first element of queue that is 5
   queue.removeFirst( ) ;    
     
   for( int i in queue ) {   
      print( i ) ;   
   }   
} 

Output :

Default implementation of ListQueue< int >
1
2
0
2

Generic Map

As we know that announcing a map requires a key and a value.

The syntax is provided below.

Syntax :

< Key_type, value_type >

Example -

void main( ) {   
Map < String, String > m = { ' Name ' : ' Yukta ' , ' Rollno ' : ' 157 ' } ;   
print( ' Map : ${ m } ' ) ;   
}  

Output :

Map : { Name : Yukta , Rollno : 157 }

Related Topics

Builder Classes in Dart

Before understanding builder classes, let us understand about Flutter that makes the best use of the builder classes. Flutter is actually not a programming language, it is a software development...

6 minutes read.

Dart Iterable

Iterable is a collection of elements that are accessed sequentially. These elements are accessible using the iterator getter and stepping through the values using this getter. Let us understand the setting...

6 minutes read.

Dart Built-in Data Types

A data type defines the type of value a variable can hold, such as integer, double, or string.  Dart supports two data types:  1. Built-in data types : These are the data...

1 minute read.

Dart Keywords

Keywords are the reserved words of a programming language, and they have a special meaning that comes defined by the language. These cannot be used as an identifier, and all...

1 minute read.

Dart Type inference

The task of interpreting the data types of fields, methods, local variables and most generic type arguments is handled by the static analyser. However, when not enough information is provided...

5 minutes read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.

Dart Features

Dart is a fully-featured, object-oriented modern language with its roots in the programming language ‘Smalltalk’. It has some of its eminent features similar to the languages such as Java, C#...

4 minutes read.

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type. Every key can occur only once, while the values can be used multiple...

5 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

Dart Generators

Synchronous Generator Dart Generator is a unique function that allows us to generate price sequences. Generators return values when needed; means that the value is generated if we try to duplicate...

5 minutes read.

Dart Miscellaneous Operators

Apart from the operators we studied so far, Dart provides some more operators which are as follows : Conditional OperatorCascade Notations Conditional Operators These are the operators that help in evaluating the expression...

1 minute read.

Dart Single-Page Application Architecture

In a single page application architecture, the source code for a single web page loads the entire application. The responsibility of building the user interface and requesting data from the...

2 minutes read.

Dart Miscellaneous types

Some Other Data types in Dart Apart from the data types studied so far, we have three other data types also which are as follows: NeverDynamicVoid Let us understand each one in detail, Never...

3 minutes read.

Dart Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable...

4 minutes read.

Dart Operators Precedence and Associativity

Precedence of operators determines the order in which the operators are evaluated if they are grouped together in a sentence. If two operators share an operand then the one with...

5 minutes read.

Dart Assignment Operator

Assignment operators are the operators that assign value to the variables. The value on the right-hand side is assigned to the variable on the left-hand side. We can also use...

4 minutes read.

Dart Comments

Comments are the statements that are used to enhance the readability and understandability of the code. The compiler does not execute these lines. It simply ignores these comments when it scans...

2 minutes read.

Type System in Dart

Dart language is a type safety enabled language that uses static and dynamic type checking to match the value of the variable with its data type at the compile-time. This...

4 minutes read.

Dart Logical Operators

Logical operators are the operators that combine two or more conditions, and accordingly return a Boolean value : true or false. Assume the value of variable A is 25 and B...

2 minutes read.

Dart Tutorial

Dart is an open-source, structured programming language developed by Google. It is a high-level programming language that emerged in 2011, but its stable version emerged in 2017. It is largely used...

4 minutes read.