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

194

Solution 1

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

enter image description here

Solution 2

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)
  
}
Share:
194
Martin
Author by

Martin

Updated on January 04, 2023

Comments

  • Martin
    Martin over 1 year

    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.

    • jamesdlin
      jamesdlin almost 2 years
      If you are okay with lookups being O(log n) instead of O(1), you can use a SplayTreeMap which keeps entries in a sorted order.
  • Ivo
    Ivo almost 2 years
    Well, your solution actually proves that the keys do have an order. Otherwise the solution wouldn't even work. It's true that maps in general don't have a key order, but the standard map in Dart does have it. But yeah, other kinds of maps in other languages might not have that.
  • Tuan
    Tuan almost 2 years
    @IvoBeckers I mean a map is used key/value then why we need order in a map