flutter - 无法更改 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;
}
解决方案
试试下面的代码,
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 获取数据并计算计数器值,然后返回计数器值。
推荐阅读
- mongodb - 在更新时更改字符串以将一些“/”放在它的中间 MongoDb
- java - 如何更改 ExpandableListView 子项中按钮的可见性?
- javascript - 尝试使用 Javascript 使视频全屏显示
- javascript - Javascript(香草)输入延迟(超时不起作用)
- c# - 匹配字符串的开头或结尾 - 但只指定一次模式
- java - Android:缩放两个视图
- prestashop - 覆盖 searchProvider.php 不起作用
- hash - Redis,按哈希查找,按字段值查找
- javascript - 如何将 setState 值插入 useEffect 挂钩?
- python - 根据用户要求的Python密码生成器问题