Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty Set in Dart

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.

like image 409
Suragch Avatar asked Aug 05 '19 22:08

Suragch


People also ask

How do you make an empty set in Flutter?

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> .

How do you create a set in Flutter?

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.

How do you define a set in darts?

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.


1 Answers

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 = {};

Notes

  • 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

like image 159
Suragch Avatar answered Sep 28 '22 15:09

Suragch