Koala
Koala

Reputation: 472

What's the best way to sort MAP<String, Object> by value in Dart programming?

I'm new to dart programming, I came from a Javascript environment everything is fresh to me and I really have no Idea how this sorting works in dart.

Here's an example from my API

List example = [
 {"id": "1", "age": "20"},
 {"id": "2", "age": "21"},
 {"id": "3", "age": "22"},
]

Before I will assign "example" to other variables eg.

var example2 = example;

I want to sort it by "age", I found libs and other "LONG" solutions out there but feels like there's another way.. Thanks in advance!

Upvotes: 0

Views: 157

Answers (1)

Cetin Basoz
Cetin Basoz

Reputation: 23807

There is sort function for list. Try reading the documentation a bit:

void main() {
List example = [
 {"id": "1", "age": "20"},
 {"id": "2", "age": "19"},
 {"id": "3", "age": "22"},
 {"id": "4", "age": "9"},
];
  print(example);
  
  example.sort((x,y) => x["age"].compareTo(y["age"]));
  print(example);
}

EDIT: Your definition should contain integers logically:

void main() {
List example = [
 {"id": 1, "age": 20},
 {"id": 2, "age": 19},
 {"id": 3, "age": 22},
 {"id": 4, "age": 9},
];
  print(example);
  
  example.sort((x,y) => x["age"].compareTo(y["age"]));
  print(example);
}

Upvotes: 1

Related Questions