August W Danowski
August W Danowski

Reputation: 135

Create a Map of Lists in Flutter

Porting an App from Swift to Flutter. In my App, I have a class, MyClass, and am dealing with a list of about 250 instances. At various times, I need to group the objects based on a particular property.

In Swift, I was able to create a grouped list of my objects like so:

var groupedList = Dictionary<String, Array<MyClass>>()

I was then able to loop through my list of objects, and assign items to the right Array as necessary. I thought it might work to make a Map of Lists in Flutter like this:

Map groupedList = Map<String, List<MyClass>>();

Then I could loop through the items, test the property, create a Map entry for each unique value and append the item to the correct List:

for (var item in listOfObjects) {
  if (!groupedList.containsKey(item.someproperty)) {
    List<MyClass> sublist = [];
    groupedList[item.someproperty] = sublist;
  }
  groupedList[item.someproperty].add(item);
}

What I get, however, is a Map with all the correct Keys, but each List contains only one instance of MyClass, rather than an actual List of MyClasses.

Upvotes: 3

Views: 4240

Answers (1)

Richard Heap
Richard Heap

Reputation: 51682

There's a more succinct syntax using putIfAbsent. This gives the results you expect:

void main() {
  var groupedList = <String, List<MyClass>>{};
  var listOfObjects = <MyClass>[
    MyClass('Europe', 'France'),
    MyClass('Europe', 'Germany'),
    MyClass('Europe', 'Italy'),
    MyClass('North America', 'USA'),
    MyClass('Asia', 'Japan'),
    MyClass('Asia', 'China'),
  ];

  for (var item in listOfObjects) {
    groupedList.putIfAbsent(item.someProperty, () => <MyClass>[]).add(item);
  }

  print(groupedList);
}

class MyClass {
  String someProperty;
  String someValue;

  MyClass(this.someProperty, this.someValue);

  @override
  String toString() => '$someProperty->$someValue';
}

Upvotes: 7

Related Questions