Home > database >  get details based on category from data in flutter?
get details based on category from data in flutter?

Time:10-02

I have some transaction datas and want to fetch category based details,

my main purpose is to learn map in dart with this same example..alomost done but here I am confused,

here are my data

List<Transaction> transactionlist=[
  Transaction(category: 'Food', amount: 100.00),
  Transaction(category: 'Food', amount: 200.00),
  Transaction(category: 'Provision', amount: 1000.00),
  Transaction(category: 'Shopping', amount: 2000.00),
  Transaction(category: 'Food', amount: 300.00),];

And I have finally got help with stack overflow user but now want bit update

here is the code I have got it...

List<Map<String, Object>> get categorybasedinfo {
    Map<String, List<Transaction>> grouped =
        groupBy(transactionlist, (value) => value.category);


    List<Transaction> result = grouped.entries
        .map((e) => Transaction(
            category: e.key,
            amount: e.value.fold(0, (total, ele) => total   ele.amount)))
        .toList();

    List<Map<String, Object>> listmap = result
        .map((e) => {
              'category': e.category,
              'amount': e.amount,
            })
        .toList();

    return listmap;

    }

this code giving me result like

[
{'category':'Food', 'amount':3999.00},
{'category:'Provision','amount:3949.00},
]

but now want to update with three key

like

{

[
{'category':'Food', 'amount':3999.00,'numberofentries':3},
{'category:'Provision','amount:3949.00,'numberofentries':1},
]

}

Thanks in advance

CodePudding user response:

First add numberofentries optionally to your model class and set its default value to 1:

class Transaction {
  final String category;
  final double amount;
  final int numberofentries;// <-----here

  Transaction(
      {required this.category, required this.amount, this.numberofentries = 1});
}

then instead of using groupBy use this:

    List<Transaction> result = [];
    for (var e in transactionlist) {
      var x = result.where((element) => element.category == e.category);
      if (x.isEmpty) {
        result.add(e);
      } else {
        var newTransaction = Transaction(
            category: e.category,
            amount: x.first.amount   e.amount,
            numberofentries: x.first.numberofentries   1);

        result[result.indexOf(x.first)] = newTransaction;
      }
    }
  • Related