Home > front end >  How to order a list of maps in dart
How to order a list of maps in dart

Time:05-22

I'm supposed to order a list of maps and I've tried everything I can think of, no breakthrough.

Here's my code:

var orgs = [
  {"name": "Google", "category": "Search Engine"},
  {"name": "Facebook", "category": "Social Media"},
  {"name": "Adidas", "category": "Sports"}
];

I want to sort this list by name. I tried using this code:

  orgs.sort((i, j) => i.name.compareTo(j.name)); //I get an error that name is not defined. only works with classes

But I get an error that name is not defined. What am I doing wrong? Or is there another approach i can try? Please assist

By the way, its important that orgs is strictly a list, not anything else!

CodePudding user response:

This should fix your problem:

 orgs.sort((i, j) => i["name"]!.compareTo(j["name"]!));

P.S Make sure the key "name" is always present in the objects.

CodePudding user response:

Your sort is comparing maps, so it needs to use the key syntax.

orgs.sort((i, j) => i['name']?.compareTo(j['name'] ?? "") ?? 1);

CodePudding user response:

The solution is defining the array as a list of maps


List<Map<String, dynamic>> orgs = [
  {"name": "Google", "category": "Search Engine"},
  {"name": "Facebook", "category": "Social Media"},
  {"name": "Adidas", "category": "Sports"}
];

This way it can then be sorted :

orgs.sort((a, b) => a["name"].compareTo(b["name"]));

The answer:

[{name: Adidas, category: Sports}, 
{name: Facebook, category: Social Media}, 
{name: Google, category: Search Engine}]
  • Related