18

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.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

2 Answers2

35

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

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • It has nothing to do with local or non-local. Both ways can be used in both local and non-local scopes. It's just two different ways of declaring variables. One with type, one without – Ivo Aug 11 '22 at 08:00
  • 2
    @Ivo, that's true. Both are permissible as far as the language is concerned. What I stated above are merely coding conventions promoted (I believe) by the Effective Dart guide. (See https://dart.dev/guides/language/effective-dart/design#types). It's been a while since I've read this thoroughly, though, and I might have been wrong to start with, so correct me if I've misunderstood the guides. And feel free to ignore the guides even if I have understood them correctly. – Suragch Aug 16 '22 at 15:45
  • you're right. It does seem to be the coding convention – Ivo Aug 17 '22 at 06:06
0

Use Set() from dart:core.

Source: https://api.dart.dev/stable/2.19.2/dart-core/Set/Set.html.

Alan
  • 1
  • 2