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.
In Dart, a
setis a particular instance of a list in which all of the inputs are unique.
dart:coreis 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.firstdoes not remove that element from the set. -
If the set is
empty, then the function throws anerror.
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 valueprint("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 valueprint("set_2 elements: ${set_2}");print("set_2 first element: ${set_2.first}");}