The set.add()
function in Dart is used to insert an element in the set.
The image below shows the visual representation of the set.add()
function:
In Dart, a set
is a particular instance of a list in which all inputs are unique.
dart:core
is required to use this function.
Note: If there are duplicates, then the set will only keep the first instance. For example:
{'Tom','Alsvin','Eddie','Tom'}
will result in{'Tom','Alsvin','Eddie'}
.
bool set_name.add(element)
// where the set_name is the name of the set.
This function requires an element
as a parameter.
This function inserts the element
sent as a parameter in the set.
It returns true
if the element is not present in the set already, otherwise returns false
.
The code below shows how to use the set.add()
function in Dart:
import 'dart:convert';import 'dart:core';void main() {Set<String> set_1 = {'Tom','Alsvin'};//set containing value before insertprint("set_1 elements before insert: ${set_1}");//inserting element in setprint("Following element is inserted in the set: ${set_1.add('Eddie')}");//set containing value after insertprint("set_1 elements after insert: ${set_1}");//trying duplicate insertionprint("Following element is inserted in the set: ${set_1.add('Alsvin')}");//set containing value after duplicate insertionprint("set_1 elements after duplicate insertion: ${set_1}");}
Line 4: We create a set with two values {'Tom','Alsvin'}
and name it set_1
.
Line 9: We add a new element Eddie
in set_1
using the add()
method.
Line 14: If we try to add a duplicate name i.e., Alsvin
, then it simply ignores it and returns the same set.