代码之家  ›  专栏  ›  技术社区  ›  W P

flutter firestore查询listen-无法引用listen中的变量

  •  0
  • W P  · 技术社区  · 7 年前

    我有一个查询来查找指定条形码的文档ID,如下所示:

    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');
            }
          }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Richard Heap    7 年前

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