Continuously add data to Map
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!
r3ck3z57
Updated on March 15, 2020Comments
-
r3ck3z57 over 4 years
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!