3

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.

1
  • Maybe you should try the queries pub, its inspired from microsoft LINQ Commented Jan 27, 2020 at 16:47

1 Answer 1

7

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';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.