我需要在for ...循环之前将数据添加到Map或HashMap,在for ...循环期间将数据添加到Map,然后在循环之后创建包含所有数据的文档。
在Java for Android中我用过:
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中的Map?
我在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>'
&#34;
提前谢谢!
答案 0 :(得分:6)
与您在Java中为Dart编写的代码相同的代码块是:
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有type inference和collection literals,因此我们可以为两者使用更简洁的语法。让我们从上面写出完全相同的东西,但是还有一些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提供的所有东西。我们可以使用地图文字而不是再写两行代码,我们甚至可以使用string interpolation:
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
“Map'`”
Dart中没有这样的语法new HashMap<>
。类型推断在没有它的情况下工作,所以你可以只写Map<String, Object> map = new HashMap()
,或者像上面的例子,var map = <String, Object> {}
,甚至更好,var map = { 'type': type }
,它会根据键输入你的地图和价值。
我希望有所帮助!