Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 947
Suragch Avatar asked Jan 07 '21 08:01

Suragch


People also ask

How do you make an empty map on Dart?

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 = {};

How do you initialize a map in Flutter?

Initialize a Map with values in Dart/Flutter initialize Map in simple way using {} (curly braces). create a Map with all key/value pairs of other Map using from() , of() constructor. create a new Map from the given keys and values using fromIterables() .


Video Answer


2 Answers

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:

  • DO use collection literals when possible.
  • Omit type annotations for local variables.
like image 155
Suragch Avatar answered Oct 22 '22 11:10

Suragch


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.

like image 26
jamesdlin Avatar answered Oct 22 '22 10:10

jamesdlin