Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map methods return List<List<Object>> Instead of List<Object>

final listTruckFruits = event.trucks
        .map((truck) => truck.fruits
            .map(
              (fruit) => TruckFruit(
                truckOrigin: truck.info.origin,
                fruitType: fruit.type,
              ),
            )
            .toList())
        .toList();

I’m trying to map multiple List<Fruit> from List<Truck>


class Truck {
  final List<Fruit> fruits;

  Truck({
    required this.fruits,
  });
}

class Fruit {
  final String type;
  Fruit({
    required this.type,
  });
}

into a List<TruckFruit> but currently what is returned from my two map methods listTruckFruits all above is a List<List<TruckFruit>> while a want List<TruckFruit>

class TruckFruit {
  final String fruitType;
  final String truckOrigin;

  TruckFruit({
    required this.fruitType,
    required this.truckOrigin,
  });
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Iterable.expand() to flatten your list of lists:

final simpleListOfAllFruitsOnAllTrucks = listTruckFruits.expand((x) => x).toList();

You could also use this to not generate a list of lists in the first place, by using it on your event.trucks instead of your first map.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading