How to create an empty Map in Dart How to create an empty Map in Dart dart dart

How to create an empty Map in Dart


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:


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.