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

后端 未结 3 1946
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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.

提交回复
热议问题