search - Flutter Firestore Query Listen - 无法从 Listen 中引用变量
问题描述
我有一个查询来查找指定条形码的 documentID,如下所示:
Future findBarcode() async {
String searchBarcode = await BarcodeScanner.scan();
Firestore.instance.collection('${newUser.userLocation}').where('barcode', isEqualTo: '${searchBarcode}').snapshots().listen(
(data) {
String idOfBarcodeValue = data.documents[0].documentID;
print(idOfBarcodeValue);
}
);
}
但是,我想在函数之外引用 idOfBarcodeValue。我正在尝试找到一种方法将其传递给另一个函数以传递给 SimpleDialog。
目前,该函数之外的任何内容都无法识别它。它确实有效,打印验证。
这是也在执行的扫描功能:
Future scan() async {
try {
String barcode = await BarcodeScanner.scan();
setState(() => this.barcode = barcode);
} on PlatformException catch (e) {
if (e.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
this.barcode = 'The user did not grant the camera permission!';
});
} else {
setState(() => this.barcode = 'Unknown error: $e');
}
} on FormatException{
setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
} catch (e) {
setState(() => this.barcode = 'Unknown error: $e');
}
}
解决方案
snapshots()
返回一个Stream<Query>
。await
与返回函数的方式相同,Future
您可以await for
使用 a 产生的所有值(可以是零、一个或多个),Stream
例如:
Future findBarcode() async {
String searchBarcode = await BarcodeScanner.scan();
String idOfBarcodeValue;
Stream<Query> stream = Firestore.instance
.collection('${newUser.userLocation}')
.where('barcode', isEqualTo: '${searchBarcode}')
.snapshots();
await for (Query q in stream) {
idOfBarcodeValue = q.documents[0].documentID;
}
print(idOfBarcodeValue);
// if the stream had no results, this will be null
// if the stream has one or more results, this will be the last result
return idOfBarcodeValue;
}
推荐阅读
- c++ - 如何在xml中使用双引号?
- javascript - Chrome 扩展访问变量
- docker - 在 Docker 容器中部署 Tomcat 时,上下文路径不起作用
- javascript - 搜索基于 JS(Highcharts、AnyChart 等)的温度计或具有多个指针的垂直线性仪表
- javascript - 在 Promise 中传递查询结果
- javascript - 在拖放列表中移动项目时出错
- javascript - Javascript 似乎不是我的 jsp 的附件
- java - Java lambdas heap dump - lambda 实例未收集垃圾
- c++ - 为什么在传递 long long 时调用具有两个 double 类型参数的重载函数?
- python - 转置嵌套生成器