34
17

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 5 years have passed since last update.

DartでListをソートする方法

Posted at

FlutterというかDartで配列の要素のプロパティでListをソートする方法を紹介します。

以下のようなEmployeeクラスがあり、このidでソートする例をとって説明します。

class Employee {
  int id;
  String name;
  Employee(this.id,this.name);
}

Listクラスはsort関数を持ちます。次のようにsort関数に比較関数を渡せば簡単に要素のプロパティでソートすることができます。

    final employees = [
      Employee(3,"Bob"),
      Employee(1,"Alice"),
      Employee(2,"John"),
    ];
    print("before sort");
    employees.forEach((employee){
      print("${employee.id}:${employee.name}");
    });
    employees.sort((a,b) => a.id.compareTo(b.id));
    print("after sort");
    employees.forEach((employee){
      print("${employee.id}:${employee.name}");
    });
    print("$employees");

結果出力はこのようになります。

I/flutter ( 3321): before sort
I/flutter ( 3321): 3:Bob
I/flutter ( 3321): 1:Alice
I/flutter ( 3321): 2:John
I/flutter ( 3321): after sort
I/flutter ( 3321): 1:Alice
I/flutter ( 3321): 2:John
I/flutter ( 3321): 3:Bob
34
17
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
34
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?