What is the set.contains() method in Dart?

The set.contains() function in Dart is used to check if a set contains the specific element sent as a parameter.

set.contains() returns true if the set contains that element. Otherwise, it returns false.

Figure below, shows a visual representation of the set.contains() function:

Visual representation of the set.contains() function

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

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


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

Syntax

bool set_name.contains(element)
// where the set_name is the name of the set.

Parameter

This function requires an element as a parameter.

Return value

The function returns a Boolean value, i.e., true if a specific element is present in a set or false if it is not present.

Code

The code below shows how to use the set.contains() function in Dart:

import 'dart:convert';
import 'dart:core';
void main() {
Set<String> set_1 = {'Tom','Alsvin','Eddie'};
//set containing value
print("set_1 elements: ${set_1}");
//set containing specific element
print("Eddie is present in the set: ${set_1.contains('Eddie')}");
//set not containing specific element
print("Jack element is present in the set: ${set_1.contains('Jack')}");
}

Free Resources