小编典典

不断向地图添加数据

flutter

我需要在for …循环之前将数据添加到Map或HashMap中,在for …循环期间将数据添加到Map中,然后在循环之后使用所有数据创建文档。

在Android版Java中,我使用了:

Map<String, Object> createDoc = new HashMap<>();
    createDoc.put("type", type);
    createDoc.put("title", title);
for (int x = 0; x < sArray.size(); x++) {
    createDoc.put("data " + x,sArray.get(x));
}
firebaseFirestoreDb.collection("WPS").add(createDoc);

我的问题是,我将如何创建文档并立即获取其ID,然后将其与其余数据进行更新/合并?还是有办法在Dart中向地图添加数据?

我在Dart中发现的唯一东西是:

Map<String, Object> stuff = {'title': title, 'type': type};

并在for …循环中:

stuff = {'docRef $x': docId};

在for …循环之后:

Firestore.instance.collection('workouts').add(stuff);

它仅使用for …循环中的最后一个条目创建一个文档。

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

Map<String, Object> newMap = new HashMap<>();

我得到的错误:"A value of type 'HashMap' can't be assigned to a variable of type 'Map<String, Object>'

先感谢您!


阅读 290

收藏
2020-08-13

共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 }它将根据键和值为您键入映射。

希望对您有所帮助!

2020-08-13