무기/다트

<Dart> 객체의 DateTime 값을 기준으로 정렬

디벅잉 2022. 10. 24. 22:26
728x90

 

🧭

 

sort

list의 sort 메서드를 활용하면 list를 정렬할 수 있습니다.

sort 메서드의 인자로는 비교함수를 대입하게 됩니다. 

단순 오름차순/내림차순의 경우에는 비교함수를 생략하고 sort() 메서드의 호출만으로 정렬이 됩니다.

sort 메서드는 원본 list를 변경하는 파괴적 메서드입니다.

 

compareTo

정렬 기준이 단순 값이 아닌 객체의 특정 프로퍼티 등인 경우에는 compareTo 함수를 통해 비교하게 됩니다.

list.sort((a, b) => a.dateTime.compareTo(b.dateTime));

DateTime 타입은 추가 가공없이 compareTo로 비교 가능합니다.

 

📌

 

https://api.flutter.dev/flutter/dart-core/List/sort.html

 

sort method - List class - dart:core library - Dart API

void sort([int compare(E a, E b )?] ) Sorts this list according to the order specified by the compare function. The compare function must act as a Comparator. final numbers = ['two', 'three', 'four']; // Sort from shortest to longest. numbers.sort((a, b) =

api.flutter.dev

 

728x90