如何在 Dart 中对列表中的项目求和

How to sum items in a List in Dart

对每个用户的所有 "expenses" 的所有 "amounts" 求和的最佳方法是什么?

我尝试了一些不同的东西,但我不太对劲。它应该 return 2 个值:20.0 和 24.90

[
  {
    "id": 3,
    "company": {
      "id": 2
    },
    "user": {
      "id": 3,
      "first_name": "Fred",
      "last_name": "Smith",
      "email": "asdfasf",
      "is_suspended": false,
      "vendor_id": "FS-100",
      "username": "etytyurtyu",
      "expense": [
        {
          "id": 7,
          "date": "2019-12-14T00:00:00.000Z",
          "amount": 20.0,
          "payment_type": "companyAccount",
          "last_modified": "2019-12-16T23:50:00.459064Z",
          "receipt_uri": [
            "URL8",
            "URL9"
          ],
          "user": {
            "id": 3
          },
          "expense_type": {
            "id": 4
          },
          "booking": {
            "id": "HI-3565346"
          }
        }
      ]
    }
  },
  {
    "id": 2,
    "company": {
      "id": 2
    },
    "user": {
      "id": 2,
      "first_name": "Pierre",
      "last_name": "XXXMar",
      "email": "asdfasdfads",
      "is_suspended": false,
      "vendor_id": "PM-100",
      "username": "asdfas",
      "expense": [
        {
          "id": 2,
          "date": "2019-12-16T00:00:00.000Z",
          "amount": 12.45,
          "payment_type": "provided",
          "last_modified": "2019-12-16T19:01:37.092932Z",
          "receipt_uri": [
            "URL1"
          ],
          "user": {
            "id": 2
          },
          "expense_type": {
            "id": 6
          },
          "booking": {
            "id": "MU-123414"
          }
        },
        {
          "id": 5,
          "date": "2019-12-08T00:00:00.000Z",
          "amount": 12.45,
          "payment_type": "provided",
          "last_modified": "2019-12-16T23:50:00.459064Z",
          "receipt_uri": [
            "URL1"
          ],
          "user": {
            "id": 2
          },
          "expense_type": {
            "id": 6
          },
          "booking": {
            "id": "MU-123414"
          }
        },
        {
          "id": 3,
          "date": "2019-12-17T00:00:00.000Z",
          "amount": 20.0,
          "payment_type": "companyCard",
          "last_modified": "2019-12-16T19:01:37.092932Z",
          "receipt_uri": [
            "URL5",
            "URL6"
          ],
          "user": {
            "id": 2
          },
          "expense_type": {
            "id": 12
          },
          "booking": {
            "id": "HI-3565346"
          }
        }
      ]
    }
  }
]

谢谢

您将首先映射费用金额,然后将其折叠成单个值,如下所示:

double sum = expenses.map((expense) => expense.amount).fold(0, (prev, amount) => prev + amount);