I have a document with fields that are generated in firebase, the field name is todays date and the value is a incremenation of a use when the user do a special thing in the app.
When i retrieve the data from firebase my Map<String, dynamic> statistics; is filled in a random order because of how data is retreived from firebase.
How can i sort the returned data on the Key value (string) so that the dates are in ascending order?
I just can not figure this out. Any hint pointers is greatly appreciated.
CodePudding user response:
var sortedKeys = map.keys.toList()..sort();
try this or use the belwo plugin
sortedmap: ^0.5.1
import 'package:sortedmap/sortedmap.dart';
main() {
var map = new SortedMap(Ordering.byValue());
map.addAll({
"a": 3,
"b": 2,
"c": 4,
"d": 1
});
print(map.lastKeyBefore("c")); // a
print(map.firstKeyAfter("d")); // b
}
import 'package:sortedmap/sortedmap.dart';
main() {
var map = new FilteredMap(new Filter(
compare: (Pair a, Pair b)=>Comparable.compare(a.value, b.value),
isValid: (Pair v) => v.key!="b",
limit: 2));
map.addAll({
"a": 3,
"b": 2,
"c": 4,
"d": 1
});
print(map.keys); // (d, a)
}
CodePudding user response:
It's key:value
bro, it doesn't exist such thing as order so it can't sort. It's a Map, just call key and it return value.
In case you really want to do this. Get keys
of the map and sort, use sorted keys to create new map in order.
void main() {
var map = {"b": {}, "d": {}, "a": {}, "h": {}, "f": {}, "c": {}};
var newmap = {};
var keys = [...map.keys]..sort((a, b) => a.compareTo(b));
for (String key in keys) {
newmap[key] = map[key];
}
print("oldmap: $map");
print("newmap: $newmap");
// result
// oldmap: {b: {}, d: {}, a: {}, h: {}, f: {}, c: {}}
// newmap: {a: {}, b: {}, c: {}, d: {}, f: {}, h: {}}
}