1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Dart/Flutter 複数キーによるSort

Posted at

Stringでcompare

MapなListを複数keyでsortするとき、valueをStringにして結合したものをsortすれば綺麗に並びます。

実装

void main(List<String> args) {
  var list = [
    {'groupId': 2, 'label': 'ロース'},
    {'groupId': 10, 'label': 'レタス'},
    {'groupId': 3, 'label': 'レモン'},
    {'groupId': 3, 'label': 'もも'},
    {'groupId': 10, 'label': 'しいたけ'},
    {'groupId': 2, 'label': 'カルビ'},
  ];

  print('sorted list:');
  // intが数字順に並ぶよう指定(例:2,3,10)
  var pairString =
      (e) => "${e['groupId'].toString().padLeft(8, '0')}"
           + "${e['label']}";
  list.sort((a, b) => pairString(a).compareTo(pairString(b)));
  list.asMap().forEach((key, value) => print("$key: $value"));
}

実行結果

sorted list:
0: {groupId: 2, label: カルビ}
1: {groupId: 2, label: ロース}
2: {groupId: 3, label: もも}
3: {groupId: 3, label: レモン}
4: {groupId: 10, label: しいたけ}
5: {groupId: 10, label: レタス}

以上

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?