22

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.

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

2 Answers2

45

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:

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

Here's how I remember the syntax:

{} is a literal, and () performs an invocation1. T{} is illegal syntax, and T() invokes the unnamed constructor for T. It doesn't matter what T is, whether it's Map<K, V> or String or any other class.

{} is a literal, but what kind of literal? Is it a Set or a Map? To distinguish between them, you should express the type. The way to express types for generics is put types in angle brackets: <K, V>{} for a Map<K, V>, and <E>{} for a Set<E>.

The same goes for Lists: [] is a literal, and you can specify the type with angle brackets: <E>[].


1 Obviously there are many other uses for {} and () in other contexts.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204