Search code examples
fluttercollectionsdartset

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.


Solution

  • 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