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.
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 = {};
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() .
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 = {};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With