如何在Dart中创建一个空地图 [英] How to create an empty Map in Dart

查看:50
本文介绍了如何在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 = {};

注意:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆