Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart flutter max value from list of objects

Tags:

flutter

dart

Looking for some help how to select oldest age from users in flutter object list...

users = [
  { id: 123, name: 'Bob', age: 25},
  { id: 345, name: 'Joe', age: 44},
  ...
];
like image 703
aknd Avatar asked Oct 15 '19 01:10

aknd


2 Answers

I'd use the list reduce function, docs here.

var oldestUser = users.reduce((currentUser, nextUser) => currentUser['age'] > nextUser['age'] ? currentUser : nextUser)
like image 53
Lebohang Mbele Avatar answered Oct 15 '22 03:10

Lebohang Mbele


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));
}
like image 30
Pablo Barrera Avatar answered Oct 15 '22 03:10

Pablo Barrera