SoFunction
Updated on 2025-04-06

Flutter list Array sorting example analysis

Sort by integer values

To use Dartsort()Method sorts List in Flutter ascending or descending order. The sort() method needs to pass a comparison function to specify how objects are compared and sort in the order you specify. Here is an example, suppose there is a list of integers that can be sorted by integer values:

List<int> numbers = [1, 3, 2, 5, 4];
// Sort ascending((a, b) => (b));
print(numbers); // Output: [1, 2, 3, 4, 5]// Sort in descending order((a, b) => (a));
print(numbers); // Output: [5, 4, 3, 2, 1]

In the above code, we use the sort() method to sort the list of numbers in ascending and descending order.

In the comparison function, we usecompareTo()Method to compare two numeric objects.

If you want to sort by other fields, just replace a and b in the comparison function with the fields you want to sort.

Sort by Person's age field

Here is the sample code, assuming you have a list of Person objects that can be sorted by Person's age field:

class Person {
  String name;
  int age;
  Person({, });
}
List<Person> persons = [
  Person(name: "John", age: 30),
  Person(name: "Jane", age: 20),
  Person(name: "Bob", age: 25),
];
// Sort by age field((a, b) => ());
// Output the sorted listprint(persons);

In the above code, we use the sort() function to sort the Person object list by age field. In this example, we use the compareTo() function to compare the age fields of the Person object and sort it in ascending order.

The above is the detailed content of Flutter list array sorting. For more information about Flutter list array sorting, please follow my other related articles!