如何计算扑扑名单上的总和?

时间:2019-11-14 06:56:26

标签: flutter dart

如果我使用此StreamBuilder调用我的snapshot.data.document

StreamBuilder(
        stream: Firestore.instance
            .collection('col')
            .document('doc')
            .snapshots(),
        builder:
            (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) {
            return new Container(
              child: Center(
                child: CircularProgressIndicator(),
              ),
            );
          } else {
            Data(document: snapshot.data.documents),
          }
        },
      ),

然后在我的类Data()中将此分数值数据称为ListView.builder

ListView.builder(
      shrinkWrap: true,
      padding: EdgeInsets.only(top: 50.0, bottom: 50.0),
      itemCount: document.length,
      itemBuilder: (BuildContext context, int i) {
         int score = document[i].data['score'];
      }
  

如何从该数据中获取总计并显示在AlertDialog中?

2 个答案:

答案 0 :(得分:0)

Future getTotal() async {
    int counter = 0;
    await Firestore.instance
        .collection('post').document('doc').collection('collection')
        .snapshots()
        .listen((data) =>
        data.documents.forEach((doc) => counter += (doc["score"])));
    print("The total is $counter");
    return counter;
  }
}

答案 1 :(得分:0)

对于未来的用户,您可以使用 fold 函数。

Future getTotal() async {
    await Firestore.instance
        .collection('post').document('doc').collection('collection')
        .snapshots()
        .listen((data) =>
        counter = data.documents.fold(0, (prev, current)) => prev + current.score;
    print("The total is $counter");
    return counter;
  }
}