I want to create an empty set for a Flutter project.
I tried this but I get an error:
Set<String> mySet = [];
Error: A value of type 'List' can't be assigned to a variable of type 'Set'.
I found an old question of mine for lists but it doesn't apply to sets.
How to create an Empty Set in Flutter or dart? An empty Set can be created in multiple ways. Normally, a Variable of type can be created using type and brackets () and optional new keyword in dart. It is an empty set without type safety and the default type is Set<dynamic> .
In order to create a set, you use the set constructor function or a Set literal. // with constructor Set<int> specialNumbers = Set(); // set literal Set<int> literalSpecialNumbers = {1, 4, 6}; Sets and maps have the the same syntax for their literal implementation.
Sets in Dart is a special case in List where all the inputs are unique i.e it doesn't contain any repeated input. It can also be interpreted as an unordered array with unique inputs. The set comes in play when we want to store unique values in a single variable without considering the order of the inputs.
You can create an empty Set a number of different ways. For a local variable use a set literal:
var mySet = <String>{};
And for a non-local variable you can use the type annotated form:
Set<String> mySet = {};
Empty lists and maps:
var myList = <String>[];
var myMap = <String, int>{};
Set literals require Dart 2.2 minimum, which you can change in your pubspec.yaml file if your current setting is below 2.2:
environment:
sdk: ">=2.2.0 <3.0.0"
Sets documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With