代码之家  ›  专栏  ›  技术社区  ›  Irfan Ganatra

从flutter中的数据中获得基于类别的详细信息?

  •  0
  • Irfan Ganatra  · 技术社区  · 4 年前

    我有一些交易数据,想获取基于类别的详细信息,

    我的主要目的是用这个例子学习飞镖中的地图。。做了很多,但现在我很困惑,

    这是我的数据

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

    我终于得到了堆栈溢出用户的帮助,但现在需要位更新

    这是我拿到的代码。。。

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

    这个代码给我的结果是

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

    但现在想用三个键更新

    喜欢

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

    提前感谢

    1 回复  |  直到 4 年前
        1
  •  1
  •   eamirho3ein    4 年前

    首先添加 numberofentries 可选地设置到您的模型类,并将其默认值设置为1:

    class Transaction {
      final String category;
      final double amount;
      final int numberofentries;// <-----here
    
      Transaction(
          {required this.category, required this.amount, this.numberofentries = 1});
    }
    

    则不使用 groupBy 使用此:

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