Sets in Dart
Sets In Dart
Set is a unique collection of items. Duplicate items are not allowed in a set. Set is unordered so it can be faster than lists while working with large data. List allows you to add duplicate items
but the set doesn’t allow duplicate items.
How To Create A Set
You can create set by using set
type annotation like: Here Set<String>
tells only Strings are allowed in the set.
void main(){
Set<String> fruits = {"Apple", "Orange", "Mango"};
print(fruits);
}
Check The Content
If you want to see set contain specific items or not, then you can use contains
method, which returns true or false.
void main(){
Set<String> fruits = {"Apple", "Orange", "Mango"};
print(fruits.contains("Mango"));
print(fruits.contains("Lemon"));
}
Add Items To Set
Like growable lists, you can add or remove items in a set. To add items use add()
method and to remove items use remove()
method.
void main(){
Set<String> fruits = {"Apple", "Orange", "Mango"};
fruits.add("Lemon");
fruits.add("Grape");
print("After Adding Lemon and Grape: $fruits");
fruits.remove("Apple");
print("After Removing Apple: $fruits");
}
Adding Multipe Elements
You can use addAll
method to add multiple elements from list to set.
void main(){
Set<int> numbers = {10, 20, 30};
numbers.addAll([40,50]);
print("After adding 40 and 50: $numbers");
}
Printing All Values In Set
You can print all items of set in dart by using for each loop or any other loop you want.
void main(){
Set<String> fruits = {"Apple", "Orange", "Mango"};
for(String fruit in fruits){
print(fruit);
}
}
Note: You cannot get set value by index number like fruits[0]
. It will give you error.