dart flutter max value from list of objects
First make sure your list has the correct type and format:
List<Map<String, dynamic>> users = [
{"id": 123, "name": "Bob", "age": 25},
{"id": 345, "name": "Joe", "age": 44},
{"id": 35, "name": "Joxe", "age": 40},
];
Then you can do this:
if (users != null && users.isNotEmpty) {
users.sort((a, b) => a['age'].compareTo(b['age']));
print(users.last['age']);
}
Another way would be:
if (users != null && users.isNotEmpty) {
dynamic max = users.first;
users.forEach((e) {
if (e['age'] > max['age']) max = e;
});
print(max['age']);
}
Another one:
if (users != null && users.isNotEmpty) {
print(users.fold<int>(0, (max, e) => e['age'] > max ? e['age'] : max));
}
And this one requires import 'dart:math'
:
if (users != null && users.isNotEmpty) {
print(users.map<int>((e) => e['age']).reduce(max));
}
I'd use the list reduce
function, docs here.
var oldestUser = users.reduce((currentUser, nextUser) => currentUser['age'] > nextUser['age'] ? currentUser : nextUser)
void main() {
var users = [
{"id": 123, "name": 'Bob', "age": 25},
{"id": 345, "name": 'Joe', "age": 44},
{"id": 35, "name": 'Joxe', "age": 40},
];
users.sort(ageCompare);
print(users.first);
}
int ageCompare(u1, u2) => u2['age'] - u1['age'];
try it on https://dartpad.dartlang.org
or just one-liner
users.sort((Map u1, Map u2) => u2['age'] - u1['age']);
print(users.first);