Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

dart - Flutter: how to sort a List of Map on basis of value?

List<Map> todos = [
        {"todo": "Walk The dog", "isDone": false},
        {"todo": "Complete Assignment", "isDone": true},
        {"todo": "Buy Groceries", "isDone": true},
        {"todo": "Gym", "isDone": false},
        {"todo": "Netflix", "isDone": false},
      ];

I want to sort the list on the basis of value of "isDone". if isDone = true, the map at that index should be moved to the bottom of the list.

question from:https://stackoverflow.com/questions/65856452/flutter-how-to-sort-a-list-of-map-on-basis-of-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Tested in dartpad...

void main() {
  List<Map> todos = [
    {"todo": "Walk The dog", "isDone": false},
    {"todo": "Complete Assignment", "isDone": true},
    {"todo": "Buy Groceries", "isDone": true},
    {"todo": "Gym", "isDone": false},
    {"todo": "Netflix", "isDone": false},
  ];
  todos.sort((a, b) => (a['isDone'] ? 1 : 0).compareTo(b['isDone'] ? 1 : 0));
  for (var v in todos.map((e) => [e['todo'], e['isDone']])) {
    print(v);
  }
}

Does not deal with missing or null values.

Update: refactored mapping function out of the comparison to ensure consistency:

void main() {
  List<Map> todos = [
    {"todo": "Walk The dog", "isDone": false},
    {"todo": "Complete Assignment", "isDone": true},
    {"todo": "Buy Groceries", "isDone": true},
    {"todo": "Gym", "isDone": false},
    {"todo": "Netflix", "isDone": false},
  ];
  int e2v (Map e) => e['isDone'] ? 1 : 0;   // map false to 0, true to 1
  todos.sort((a, b) => (e2v(a).compareTo(e2v(b))));
  for (var v in todos.map((e) => [e['todo'], e['isDone']])) {
    print(v);
  }
}

Idea: sort should have a cousin for which the interface might look like

todos.sortBy((e) => e['isDone'] ? 1 : 0);

And watch, two hours later, I'll see how to do it with built-ins. :)

Edit: OK, 45 minutes and I've got this, but it's missing the generics:

void main() {
  List<Map> todos = [
    {"todo": "Walk The dog", "isDone": false},
    {"todo": "Complete Assignment", "isDone": true},
    {"todo": "Buy Groceries", "isDone": true},
    {"todo": "Gym", "isDone": false},
    {"todo": "Netflix", "isDone": false},
  ];
  todos.sortBy((e) => e['isDone'] ? 1 : 0);
  for (var v in todos.map((e) => [e['todo'], e['isDone']])) {
    print(v);
  }
}

extension ListSortBy on List {
  void sortBy(mapper(e)) {
    this.sort((a, b) => mapper(a).compareTo(mapper(b)));
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...