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.
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!