Dart Set add()
Syntax & Examples
Set.add() method
The `add` method in Dart adds a value to a Set.
Syntax of Set.add()
The syntax of Set.add() method is:
bool add(E value)
This add() method of Set adds value to the set.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
value | required | The value to be added to the set. |
Return Type
Set.add() returns value of type bool
.
✐ Examples
1 Adding an integer to a set of integers
In this example,
- We create a Set variable
numbers
containing integer elements. - We use the
add()
method to add the value 4 to the set. - We print whether the addition was successful and the updated set to standard output.
Dart Program
void main() {
Set<int> numbers = {1, 2, 3};
bool added = numbers.add(4);
print('Value added successfully: $added');
print('Updated set: $numbers');
}
Output
Value added successfully: true Updated set: {1, 2, 3, 4}
2 Adding a string to a set of strings
In this example,
- We create a Set variable
fruits
containing string elements. - We use the
add()
method to add the value 'kiwi' to the set. - We print whether the addition was successful and the updated set to standard output.
Dart Program
void main() {
Set<String> fruits = {'apple', 'banana', 'orange'};
bool added = fruits.add('kiwi');
print('Value added successfully: $added');
print('Updated set: $fruits');
}
Output
Value added successfully: true Updated set: {'apple', 'banana', 'orange', 'kiwi'}
Summary
In this Dart tutorial, we learned about add() method of Set: the syntax and few working examples with output and detailed explanation for each example.