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

Time:07-12

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,
  });
}

CodePudding user response:

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.

CodePudding user response:

You could use fold:

  final result = event.trucks.fold<List<TruckFruit>>([], (acc, truck) {
    acc.addAll(truck.fruits
        .map((f) => TruckFruit(truckOrigin: truck.origin, fruitType: f.type)));
    return acc;
  });
  • Related