Dart/Flutter – How to group items in a List

In this article, we learn how to group items in a list using collection package in Dart or if you are on Flutter, we use existing collection library.

Suppose we have a list of employees and we want to group them by country.

If you are in Dart project, you need to add the collection package to your pubspec.yaml:

dependencies:
  collection: ^1.14.13

Firstly, we create Employee class. In this class, we override toString method to format the output when we print an employee. If you are not sure why we need to do that, this article will help you.

class Employee {
  final String name;
  final String country;
  final String city;

  Employee({this.name, this.country, this.city});

  @override
  String toString() {
    return '{$name, $country, $city}';
  }
}

Next step, let’s create a list of employees in our main method:

void main() {
  final employees = <Employee>[
    Employee(name: 'Phuc', country: 'Vietnam', city: 'Ho Chi Minh'),
    Employee(name: 'Ronaldo', country: 'Vietnam', city: 'Hanoi'),
    Employee(name: 'Rooney', country: 'England', city: 'Manchester'),
    Employee(name: 'Messi', country: 'Vietnam', city: 'Ho Chi Minh'),
    Employee(name: 'Rashford', country: 'England', city: 'Manchester'),
    Employee(name: 'Lampard', country: 'England', city: 'London'),
  ];
}

Write a method to group employees by country:

void groupEmployeesByCountry(List<Employee> employees) {
  final groups = groupBy(employees, (Employee e) {
    return e.country;
  });

  print(groups);
}
// Output

{Vietnam: [
    {Phuc, Vietnam, Ho Chi Minh}, 
    {Ronaldo, Vietnam, Hanoi}, 
    {Messi, Vietnam, Ho Chi Minh}
], 
England: [
    {Rooney, England, Manchester}, 
    {Rashford, England, Manchester}, 
    {Lampard, England, London}
]}

As you can see, the country name is used as a key, the value is a list of all employees who have/match that country name.

When you want to group the list by multiple fields, you just need to combine them in the return. Example below demonstrates how to group employees by country and city:

void groupEmployeesByCountryAndCity(List<Employee> employees) {
  final groups = groupBy(employees, (Employee e) {
    return '${e.country}+${e.city}';
  });

  print(groups);
}
// Output

{Vietnam+Ho Chi Minh: [ 
    {Phuc, Vietnam, Ho Chi Minh},  
    {Messi, Vietnam, Ho Chi Minh}
], 
Vietnam+Hanoi: [
    {Ronaldo, Vietnam, Hanoi}
], 
England+Manchester: [
    {Rooney, England, Manchester}, 
    {Rashford, England, Manchester}
], 
England+London: [
    {Lampard, England, London}
]}

If you are looking for mobile/web Software Engineers to build you next projects, pleaseĀ Drop us your request!

Tagged : / / / /
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x