What is the set.first method in Dart?

The set.first function in Dart is used to get the reference of the first element in the set.

The image below shows the visual representation of the set.first function.

Visual representation of the set.first function

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

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


If there are duplicates, then the set will only keep the first instance. For instance, {'Tom','Alsvin','Eddie','Tom'} will result in {'Tom','Alsvin','Eddie'}.

Syntax

element set_name.first
// where the set_name is the name of the set.

Parameter

This function does not require a parameter.

Return value

The set.first function returns the reference to the set’s first element.

  • set.first does not remove that element from the set.

  • If the set is empty, then the function throws an error.

Code

The code below shows how to use the set.first 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 elements: ${set_1}");
print("set_1 first element: ${set_1.first}");
Set<String> set_2 = {'Tom','Alsvin','Eddie','Tom'};
//set containing non-unique value
print("set_2 elements: ${set_2}");
print("set_2 first element: ${set_2.first}");
}

Free Resources