如何在Dart中创建一个空地图
问题描述:
我总是忘记如何在Dart中创建空白地图.这不起作用:
I'm always forgetting how to create an empty map in Dart. This doesn't work:
final myMap = Map<String, dynamic>{};
没关系:
final myMap = Map<String, dynamic>();
但是我收到警告,请尽可能使用集合文字.
But I get a warning to use collection literals when possible.
我在下面添加我的答案,以便下次我忘了它.
答
您可以使用地图文字来创建空的 Map
:
You can create an empty Map
by using a map literal:
{}
但是,如果类型未知,它将默认为 Map<动态,动态>
,这会破坏类型安全性.为了指定局部变量的类型,您可以执行以下操作:
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 = {};