Search code examples
dartcollectionshashmap

How to create an empty Map in Dart


I'm always forgetting how to create an empty map in Dart. This doesn't work:

final myMap = Map<String, dynamic>{};

This is ok:

final myMap = Map<String, dynamic>();

But I get a warning to use collection literals when possible.

I'm adding my answer below so that it'll be here the next time I forget.


Solution

  • You can create an empty Map by using a map literal:

    {}
    

    However, if the type is not already known, it will default to Map<dynamic, dynamic>, which defeats type safety. In order to specify the type for a local variable, you can do this:

    final myMap = <String, int>{};
    

    And for non-local variables, you can use the type annotation form:

    Map<String, int> myMap = {};
    

    Notes: