如何在Dart中创建一个空地图 [英] How to create an empty Map in Dart
本文介绍了如何在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 = {};
注意:
- 在以下情况下,DO使用集合文字可能.
- 省略局部变量的类型注释.
这篇关于如何在Dart中创建一个空地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文