Here i have multiple nested class data and i want to get sum of SelectedProductServices.count

my data class started with OrderStructure which that have a list as SelectedProducts and each of them have SelectedProductServices which count is here. now how can i use fold or reduce to get sum of them?

for example:

order.products.map((p)=>p.services.fold(0,(a,b)=>a!+b))

should return 600

my code:

void main() {
     OrderStructure order = OrderStructure('test',<SelectedProducts>[
      SelectedProducts(
          1, <SelectedProductServices>[
        const SelectedProductServices(1, 100, 1),
        const SelectedProductServices(1, 500, 1),
      ]
      )
    ]);

    getSum();
}

void getSum(){
   return order.products.map((p)=>p.services.fold(0,(a,b)=>a!+b));
}

class OrderStructure {
  final String title;
  final List<SelectedProducts> products;

  const OrderStructure(this.title, this.products);
}

class SelectedProducts {
  final int id;
  final List<SelectedProductServices> services;

  SelectedProducts(this.id, this.services);
  @override
  bool operator ==(other) => other is SelectedProducts && other.id == id;

  @override
  int get hashCode => id.hashCode;
}

class SelectedProductServices {
  final int id;
  final int count;
  final int cost;

  const SelectedProductServices(this.id, this.count, this.cost);
}


Solution 1: t00n

This should do it

int getSum(){
     return order.products.map((p) => p.services.fold(0, (int a, b) => a + b.count)).first;
}


Solution 2: TmKVU

Since you have nested list, you'd have to fold twice to get a single value:

int getSum(){
   int sum(int a, SelectedProductServices s) => a + s.count;
   return order.products.map((p) => p.services.fold(0, sum)).fold(0, (a,b) => a + b);
}