How to find min and max value in Dart List? Flutter List| Dart By Example
A List contains multiple values; sometimes, you need to obtain the minimum and maximum values from the given list.
How to find the maximum and minimum values of a List of Numbers in a Dart program?
Let’s explore some programs to find the minimum and maximum values in different ways.
use
Sort
the list and get the first and last Element in DartIn this example, first, sort the list of numbers using the
sort()
method. This arranges the numbers in ascending order. The first element becomes the minimum value, and the last element is the maximum value.Here’s an example Dart code to find the minimum and maximum values using sorting.
main() { List numbers = [8, 1, 0, 2, 102, 5]; numbers.sort(); print(numbers); // [0, 1, 2, 5, 8, 102] print(numbers[0]); //0 print(numbers[numbers.length - 1]); //102 }
Using the Reduce Method
The
reduce
method in a list is used to reduce the collection of items into a single value using a logic defined inside a function.Here is a Syntax.
reduce(combinedFunction)
The
combinedFunction
holds the current value and the next value, compares the values, and assigns the current value with minimum or maximum logic.Here’s an example program.
main() { List numbers = [8, 1, 0, 2, 102, 5]; var maximumNumber = numbers.reduce((value, element) => value > element ? value : element); var minimumNumber = numbers.reduce((value, element) => value < element ? value : element); print(maximumNumber); // 102 print(minimumNumber); // 0 }
How to get the max and min values from a list of objects?
In this scenario, we have a list of employees, where each employee holds name and salary information. This program finds the minimum and maximum salary of all employees listed in Dart and Flutter programming.
class Employee {
final String name;
final int salary;
Employee(this.name, this.salary);
@override
String toString() {
return 'Employee: {name: ${name}, salary: ${salary}}';
}
}
final e1 = Employee('Erwin', 9000);
final e2 = Employee('Andrew', 70000);
final e3 = Employee('Mark', 8000);
final e4 = Employee('Otroc', 5000);
main() {
List<Employee> employees = [e1, e2, e3, e4];
// Find Employee having minimum salary from all employees
Employee employeeWithMinSalary = employees
.reduce((item1, item2) => item1.salary < item2.salary ? item1 : item2);
print(employeeWithMinSalary.toString()); // 102
// Find Employee having Maximum salary from all employees
Employee employeeWithMaxSalary = employees
.reduce((item1, item2) => item1.salary > item2.salary ? item1 : item2);
print(employeeWithMaxSalary.toString()); // 102
}
Output:
Employee: {name: Otroc, salary: 5000}
Employee: {name: Andrew, salary: 70000}
Conclusion
In summary, we learned how to find the minimum and maximum values of a list in Dart and Flutter programming, covering
- Lists of primitive numbers.
- Lists of objects based on a numeric property.