Query a single document from Firestore in Flutter (cloud_firestore Plugin)

后端 未结 3 1936
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 07:51

I want to retrieve data of only a single document via its ID. My approach with example data of:

TESTID1 {
     \'name\': \'example\', 
              


        
相关标签:
3条回答
  • 2020-12-01 08:07

    If you want to use a where clause

    await Firestore.instance.collection('collection_name').where(
        FieldPath.documentId,
        isEqualTo: "some_id"
    ).getDocuments().then((event) {
        if (event.documents.isNotEmpty) {
            Map<String, dynamic> documentData = event.documents.single.data; //if it is a single document
        }
    }).catchError((e) => print("error fetching data: $e"));
    
    0 讨论(0)
  • 2020-12-01 08:10

    but that does not seem to be correct syntax.

    It is not the correct syntax because you are missing a collection() call. You cannot call document() directly on your Firestore.instance. To solve this, you should use something like this:

    var document = await Firestore.instance.collection('COLLECTION_NAME').document('TESTID1');
    document.get() => then(function(document) {
        print(document("name"));
    });
    

    Or in more simpler way:

    var document = await Firestore.instance.document('COLLECTION_NAME/TESTID1');
    document.get() => then(function(document) {
        print(document("name"));
    });
    

    If you want to get data in realtime, please use the following code:

    Widget build(BuildContext context) {
      return new StreamBuilder(
          stream: Firestore.instance.collection('COLLECTION_NAME').document('TESTID1').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return new Text("Loading");
            }
            var userDocument = snapshot.data;
            return new Text(userDocument["name"]);
          }
      );
    }
    

    It will help you set also the name to a text view.

    0 讨论(0)
  • 2020-12-01 08:31

    This is simple you can use a DOCUMENT SNAPSHOT

    DocumentSnapshot variable = await Firestore.instance.collection('COLLECTION NAME').document('DOCUMENT ID').get();
    

    You can access its data using variable.data['FEILD_NAME']

    0 讨论(0)
提交回复
热议问题