简体   繁体   中英

Sort Map<String, dynamic> in flutter dart where the first key is the field name

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.

var sortedKeys = map.keys.toList()..sort();

try this or use the below 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)
  
}

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: {}}
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM