Flutter Firestore查询监听-无法从监听引用变量

时间:2018-07-17 00:09:16

标签: search dart google-cloud-firestore flutter

我有一个查询来查找指定条形码的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');
        }
      }

2 个答案:

答案 0 :(得分:0)

snapshots()返回一个Stream<Query>。用与await返回Future的函数相同的方式,您可以await for 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;
}

答案 1 :(得分:0)

我认为我应该修改 Richard Heap 中的代码,这是我在2020年3月7日发布的有关条形码扫描的最新代码,如果您想从条形码中获取价值,可以将其用于条形码扫描

String barcode = "";
Future scan() async {
try {
  barcode = await BarcodeScanner.scan();
  setState(() => this.barcode = barcode);

  String idOfBarcodeValue;
  Stream<QuerySnapshot> stream = dbReference
      .collection('userLocation')
      .where('qrCodeNumber', isEqualTo: barcode)
      .snapshots();
  await for (QuerySnapshot q in stream) {
    idOfBarcodeValue = q.documents[0].documentID;
    print(idOfBarcodeValue);
  }

} 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 = 'User after click "back"-button before result');
} catch (e) {
  setState(() => this.barcode = 'Unknown error: $e');
}