如何从Firestore文档的一个字段中获取数据?

时间:2020-04-18 11:15:53

标签: flutter dart google-cloud-firestore

因此,我正在开发一个应用程序,该应用程序扫描条形码并在Firestore数据库中搜索ID与扫描的条形码匹配的文档,然后将数据添加到地图列表中。

但是我卡住了,因为我不知道如何将文档中仅一个字段的值分配给地图中的正确键

以下是相关代码:

Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
    var databaseSearchResult = firestore.collection("packages").document(barcode);
    String databaseID =
        firestore.collection("packages").document(barcode).documentID;
    if (databaseID == barcode) {
      setState(() {
        productList.add({
          "bruh": databaseSearchResult["bruh"],
          "bruh 2": databaseSearchResult["bruh 2"]
        });
      });
    }
    } catch (e) {
      Fluttertoast.showToast(msg: "Object not found in database");
    }
    try {} 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 个答案:

答案 0 :(得分:1)

您必须获取文档的数据,但此处未做此操作。尝试以下代码:

Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
    var databaseSearchResult = firestore.collection("packages").document(barcode);
    DocumentSnapshot documentData = await databaseSearchResult.get() //read the data from the document
    Map<String,dynamic> dataMap = documentData.data; //this returns the data as a map where keys are the field names and values are the values of that field
    String databaseID =
        firestore.collection("packages").document(barcode).documentID;
    if (databaseID == barcode) {
      setState(() {
        productList.add({
          "bruh": dataMap["bruh"], //you access the value of "bruh" field in your database
          "bruh 2": dataMap["bruh 2"]
        });
      });
    }
    } catch (e) {
      Fluttertoast.showToast(msg: "Object not found in database");
    }
    try {} 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');
    }
  }