Continuously add data to Map

时光毁灭记忆、已成空白 提交于 2019-12-10 14:53:58

问题


I need to add data to a Map or HashMap before a for...loop, add data to the Map during the for...loop and then create the document with all of the data after the loop.

In Java for Android I used:

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);

My question is, how would I create the document and immediately get the ID of it to then update/merge it with the rest of the data? Or is there a way to add data to a Map in Dart?

The only thing I've found in Dart is:

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

and in the for...loop:

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

and after the for...loop:

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

which creates a document with only the last entry from the for...loop.

I also imported dart:collection to use HashMap, but it won't let me use

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<String, Object>'"

Thank you in advance!


回答1:


An equivalent block of code to what you wrote in Java, for Dart, is:

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];
}

Of course, Dart has type inference and collection literals, so we can use a more short-hand syntax for both. Let's write the exact same thing from above, but with some more Dart (2) idioms:

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

OK, that's better, but still is not using everything Dart provides. We can use the map literal instead of writing two more lines of code, and we can even use string interpolation:

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

I also imported dart:collection to use HashMap, but it won't let me use

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'`"

There is no such syntax new HashMap<> in Dart. Type inference works without it, so you could just write Map<String, Object> map = new HashMap(), or like my above example, var map = <String, Object> {}, or even better, var map = { 'type': type }, which will type the map for you based on the key and value.

I hope that helps!



来源:https://stackoverflow.com/questions/49291203/continuously-add-data-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!