首页 > 解决方案 > 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');
        }
      }

标签: searchdartgoogle-cloud-firestoreflutter

解决方案


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;
}

推荐阅读