不断向地图添加数据

不断向地图添加数据,第1张

不断向地图添加数据

与您为Dart用Java编写的代码等效的代码块是:

Map<String, Object> createDoc = new HashMap();createDoc['type'] = type;createDoc['title'] = title;for (int x = 0; x < sArray.length; x++) {  createDoc['data' + x] = sArray[x];}

当然,Dart具有类型推断和集合文字,因此我们可以对两者使用更简化的语法。让我们从上面写出完全相同的东西,但是还有更多的Dart(2)习惯用法:

var createDoc = <String, Object>{};createDoc['type'] = type;createDoc['title'] = title;for (var x = 0; x < sArray.length; x++) {  createDoc['data' + x] = sArray[x];}

好的,那更好,但是仍然没有使用Dart提供的所有功能。我们可以使用map文字而不是再写两行代码,甚至可以使用字符串插值:

var createDoc = {  'type': type,  'title': title,};for (var x = 0; x < sArray.length; x++) {  createDoc['data$x'] = sArray[x];}

我还导入了dart:collection以使用HashMap,但它不允许我使用

Map<String, Object> newMap = new HashMap<>(); I get the error: `"A value

of type ‘HashMap’ can’t be assigned to a variable of type

“地图”`”

new HashMap<>
Dart中没有这样的语法。没有它,类型推断就可以工作,因此您可以编写
Map<String, Object> map =new HashMap()
,或者像上面的示例一样,
var map = <String, Object> {}
甚至更好,,
var map = {'type': type }
它将根据键和值为您键入映射。

希望对您有所帮助!



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4945583.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-13
下一篇2022-11-13

发表评论

登录后才能评论

评论列表(0条)

    保存