6
5

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.

FlutterのList<Map<String,dynamic>>をintやDateTimeでsortする

6
Last updated at Posted at 2021-10-15

数字が大きい順

void sort() {
  final List<Map<String,dynamic>> list = [
    {'score': 1},
    {'score': 2},
    {'score': 3}
  ];
  list.sort((a,b) => b['score'].compareTo(a['score']));
  print(list);
}
  

結果

[{score: 3}, {score: 2}, {score: 1}]

数字が小さい順

void sort(){
  final List<Map<String,dynamic>> list = [
    {'score': 1},
    {'score': 2},
    {'score': 3}
  ];
  list.sort((a,b) => a['score'].compareTo(b['score']));
  print(list);
}

結果

[{score: 1}, {score: 2}, {score: 3}]

新しい順

void sort(){
  final firstDay = DateTime(2021,10,10);
  final nextDay = DateTime(2021,10,11);
  final nextNextDay = DateTime(2021,10,12);
  final List<Map<String,dynamic>> timeStamps = [
    {'createdAt': firstDay},
    {'createdAt': nextDay},
    {'createdAt': nextNextDay}
  ];
  timeStamps.sort((a,b) => b['createdAt'].compareTo(a['createdAt']));
  print(timeStamps);
}

結果

[{createdAt: 2021-10-12 00:00:00.000}, {createdAt: 2021-10-11 00:00:00.000}, {createdAt: 2021-10-10 00:00:00.000}]

古い順

void sort(){
  final firstDay = DateTime(2021,10,10);
  final nextDay = DateTime(2021,10,11);
  final nextNextDay = DateTime(2021,10,12);
  final List<Map<String,dynamic>> timeStamps = [
    {'createdAt': firstDay},
    {'createdAt': nextDay},
    {'createdAt': nextNextDay}
  ];
  timeStamps.sort((a,b) => a['createdAt'].compareTo(b['createdAt']));
  print(timeStamps);
}

結果

[{createdAt: 2021-10-10 00:00:00.000}, {createdAt: 2021-10-11 00:00:00.000}, {createdAt: 2021-10-12 00:00:00.000}]
6
5
0

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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?