skip to Main Content

Let’s say I have:

List<Thing> myList = …

And Thing is a class that includes:

String a;
List<String> b;
…

Is it possible to map myList in a way that generates a List<String> that includes all a and all b?

I want to end up with a List<String> with all values of a and all values of b.

Something like:

myList.map((e) => ????).toList()

Currently what I do is create a separate List secondList and then loop through both lists like this:

myList.forEach((e) {
  secondList.add(e.a);
  e.b.forEach((x) => secondList.add(x));
});

But it’s a bit cumbersome. Thanks for any tips!

2

Answers


  1. You can use expand to convert these data into single list

    List<String> secondList = list.expand((element) => [element.a, ...element.b]).toList();
    

    Or, you can also use for and addAll

    myList.forEach((e) {
      secondList.add(e.a);
      secondList.addAll(e.b);
    });
    
    Login or Signup to reply.
  2. In general, Iterable.map usually can be replaced with collection-for. In this case, that would be much simpler since that also would let you use the spread (...) operator:

    var everything = [
      for (var thing in myList)
        ...[thing.a, ...thing.b],
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search