首页 > 解决方案 > 无法更改 void 函数内的数据

问题描述

我试图在每次通过 for 函数时添加到名为 counter 的 int 变量,但它似乎没有加起来,因为它不在范围内。

int test(String carNumber) {
    int counter = 0;

    Firestore.instance
        .collection('Notes')
        .document('LoanedEquipments')
        .collection(carNumber)
        .getDocuments()
        .then((QuerySnapshot snapshot) {
      snapshot.documents.forEach((f) {
        print(f.data['Items']);
        counter++;
      });
    });
    return counter;
  }

标签: flutterdartgoogle-cloud-firestore

解决方案


试试下面的代码,

Future<int> test(String carNumber) async {
    int counter = 0;

    QuerySnapshot snapShot=await Firestore.instance
        .collection('Notes')
        .document('LoanedEquipments')
        .collection(carNumber)
        .getDocuments();

    if(snapShot!=null){
      snapShot.documents.forEach((f) {
        print(f.data['Items']);
        counter++;
      });
    }

    return counter;
  }

当您在 then 方法中更新计数器值时,您没有得到适当的计数器值,该方法将在您的 Querysnapshot 数据从 firebase 之后调用。

您的 Querysnapshot 需要一些时间来从 firebase 查询数据。因此,在获取 Querysnapshot 数据之前,您的方法会返回您的初始计数器值。

因此,使用 await 方法等待 Querysnapshot 从 firebase 获取数据并计算计数器值,然后返回计数器值。


推荐阅读