Sunshine
Sunshine

Reputation: 334

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

Upvotes: 0

Views: 58

Answers (2)

Roger Lipscombe
Roger Lipscombe

Reputation: 91835

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

Upvotes: 1

nvoigt
nvoigt

Reputation: 77304

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.

Upvotes: 1

Related Questions