in the following code I'm trying to transform between map to set so I used list as a middle since set doesn't allow keys and values I know there is easier ways to transform between these 2 but I want to know why it gave me "false" when I ran the script
void main() {
List a = [];
Map info = {"name": "mark", "age": "20"};
info.forEach((key, value) {
a.add(value);
});
a.toSet;
print(a is Set);
}
CodePudding user response:
You've declared variable type of a
as List, Therefor it will only can have list.
To convert set, use .toSet()
.
Now let say we still want to assign set inside a
variable. In this case we can use dynamic
data type.
void main() {
dynamic a = [];
Map info = {"name": "mark", "age": "20"};
info.forEach((key, value) {
a.add(value);
});
a = a.toSet();
print(a is Set);
}
You can find more about dart type-system.
CodePudding user response:
Your code is printing false
because the type of your variable a
is still a List
object.
If you check the documentation of the method toSet
you will see that its prototype is the following:
Set<E> toSet()
The method toSet
is not changing the type of your variable from List
to Set
, its returning a new value which you will have to keep inside another variable.
As mentioned by Yeasin you are declaring your variable a
as List
, to convert it to a Set
object you can either type a
as Set
when declaring it:
Set a = {};
or, as you've tried, call the method toSet()
but you will need to keep the return value in a new variable:
final mySet = a.toSet();
Note that instead of using a forEach
you could directly convert as a Set
your map by using the getter values
:
Map info = {"name": "mark", "age": "20"};
final a = info.values.toSet();
print(a is Set);