What is the set.length method in Dart?

In Dart, a set is a particular instance of a list in which all of the elements are unique.

If there are duplicates, the set only keeps the first instance. For example, {'Tom','Alsvin','Eddie','Tom'} results in {'Tom','Alsvin','Eddie'}

The length function in Dart for sets returns the number of elements in a set. In short, this function is used to get the current size of a set.

dart:core is required in-order to use this function.

Figure 1 shows the visual representation of the length function:

Figure 1: Visual representation of set.length function

Syntax

int set_name.length
// where the set_name is the name of the set

Parameter

This function does not require a parameter.

Return value

This function returns the number of elements in a set and is used to get the current size of a set.

Code

The following code shows how to use set.length function in Dart:

import 'dart:convert';
import 'dart:core';
void main() {
Set<String> set_1 = {'Tom','Alsvin','Eddie'};
//set containing unique value
print("set_1 length: ${set_1.length}");
//empty set
Set<String> set_2 = {};
print("set_2 length: ${set_2.length}");
//set containing non-unique value
Set<String> set_3 = {'Tom','Alsvin','Eddie','Tom'};
print("set_3 length: ${set_3.length}");
}

Free Resources