【问题标题】:How do I add items of multiple arrays with respect to their indexes in dart?如何在 dart 中根据它们的索引添加多个数组的项目?
【发布时间】:2021-02-26 07:11:55
【问题描述】:

代码:

  void func({String value}) async {
   
      final QuerySnapshot snapshot = await _firestore
          .collection('users')
          .where("id", isEqualTo: signedInUser.id)
          .get();

      snapshot.docs.forEach((element) {
        List<dynamic> arr = element.data()["array"];

        print(arr);

        }
}

输出:

I/flutter (27759): [10, 20, 30, 33, 34, 24]
I/flutter (27759): [2, 42, 45, 23, 85, 51]
I/flutter (27759): [32, 53, 12, 67, 34, 23]

这是我从 Firebase 文档打印列表时得到的结果。

如何为每个索引添加数组项?喜欢;索引 0 为 10 + 2 + 32

【问题讨论】:

  • 我无法理解您的问题?你能举个例子说明你想要的结果吗?
  • 我已经更新了问题。现在清楚了吗?

标签: arrays list dart indexing add


【解决方案1】:

您应该能够获得 Lists 的 List,然后使用 for 循环对数据求和,例如:

var lists = snapshot.docs.map((e) => e.data()['array']);
var sums = <int>[];
for (int i = 0; i < lists.first.length; i++) {
  var sum = 0;
  for (var list in lists) {
     sum += list[i];
  }
  sums.add(sum);
}

请注意,此代码未经测试,您需要确保列表长度相等,否则代码可能无法按预期工作/引发异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多