Home > Back-end >  fold method not working while applying after toList() method in flutter
fold method not working while applying after toList() method in flutter

Time:11-26

I am getting an error when I apply fold() method after toList()

I have a list of Map that contains data regarding income and expense and here I want to generate a report that contains monthly basis data like monthly total_expenses and total_income,

I have solved with my way but looking for good coding and want to know how to use fold with toList in a single line statement

List<Map<String, dynamic>> datalist = [
  {'date': DateTime(2022, 10, 7), 'isExpense': true, 'amount': 343.00},
  {'date': DateTime(2022, 10, 12), 'isExpense': false, 'amount': 424.00},
  ....
];

List<Map<String, dynamic>> reportlist = [];

getReport() {
  final months = datalist.map((e) => e['date'].month).toSet();

  int m = 0;
  double expense_sum = 0;
  double income_sum = 0;
  double netbalance = 0;

  for (var m in months) {
    
   /*
   this following statement does not work and showing error at
    previousValue element['amount'];
    
    final answer = datalist
        .where((element) =>
    element['date'].month == m && element['isExpense'] == true)
        .toList().fold(
        0, (previousValue, element) => previousValue   element['amount']);
        
        
        and thats why i hve to divide code in two part,
        first fetching expense records and than applying fold to that list;
        

    */
    final expenselist = datalist
        .where((element) =>
            element['date'].month == m && element['isExpense'] == true)
        .toList();

    expense_sum = expenselist.fold(
        0, (previousValue, element) => previousValue   element['amount']);



    final incomelist = datalist
        .where((element) =>
            element['date'].month == m && element['isExpense'] == false)
        .toList();
    income_sum = incomelist.fold(
        0, (previousValue, element) => previousValue   element['amount']);

    reportlist.add({
      'Month': m,
      'totalExpense': expense_sum,
      'totalIncome': income_sum,
      'netBalance': income_sum - expense_sum,
    });
  }
}



my output will be like {
      'month': 11,
      'totalExpense': 1200,
      'totalIncome': 2000,
      'netBalance': 800,
}



CodePudding user response:

When you define a variable like final answer that means its value gonna choose its type. but when you use fold without define its type you get that error. You need to define fold type which is double, like this:

final answer = datalist
          .where((element) =>
              element['date'].month == m && element['isExpense'] == true)
          .toList()
          .fold<double>(
              0, (previousValue, element) => previousValue   element['amount']);
  • Related