如何从flutter中的firestore文档字段获取数据?

Rus*_*koz 7 dart firebase flutter google-cloud-firestore

我正在尝试在我的 flutter-app 中测试 firestore,但我无法真正按预期加载数据。

这是我获取数据的方式:

 Firestore.instance
        .collection('Test')
        .document('test')
        .get()
        .then((DocumentSnapshot ds) {
      // use ds as a snapshot

      print('Values from db: $ds');
    });
Run Code Online (Sandbox Code Playgroud)

和打印语句输出:flutter: Values from db: Instance of 'DocumentSnapshot'。

我也尝试了以下操作,但没有成功:

Firestore.instance.collection('Test').document('test').get().then((data) {
  // use ds as a snapshot

  if (data.documentID.length > 0) {
    setState(() {
      stackOver = data.documentID;
      print(stackOver);
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

这里的输出只是documentID-name..

那么,我怎么能从 firestore 中获取字段值呢?

此致!

Muh*_*man 8

尝试这个:

final String _collection = 'collectionName';
final Firestore _fireStore = Firestore.instance;

getData() async {
  return await _fireStore.collection(_collection).getDocuments();
}

getData().then((val){
    if(val.documents.length > 0){
        print(val.documents[0].data["field"]);
    }
    else{
        print("Not Found");
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 5

我遇到了类似的问题并以这种方式解决了它:

Stream<DocumentSnapshot> provideDocumentFieldStream() {
    return Firestore.instance
        .collection('collection')
        .document('document')
        .snapshots();
}
Run Code Online (Sandbox Code Playgroud)

之后,我使用 StreamBuilder 来使用上面创建的方法:

StreamBuilder<DocumentSnapshot>(
    stream: provideDocumentFieldStream(),
    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.hasData) {
            //snapshot -> AsyncSnapshot of DocumentSnapshot
            //snapshot.data -> DocumentSnapshot
            //snapshot.data.data -> Map of fields that you need :)

            Map<String, dynamic> documentFields = snapshot.data.data;
            //TODO Okay, now you can use documentFields (json) as needed

            return Text(documentFields['field_that_i_need']);
        }
    }
)
Run Code Online (Sandbox Code Playgroud)


Cop*_*oad 5

空安全代码:

  • 一次性读取数据:

    var collection = FirebaseFirestore.instance.collection('users');
    var docSnapshot = await collection.doc('some_id').get();
    if (docSnapshot.exists) {
      Map<String, dynamic> data = docSnapshot.data()!;
    
      // You can then retrieve the value from the Map like this:
      var name = data['name'];
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 持续监听数据:

    var collection = FirebaseFirestore.instance.collection('users');
    collection.doc('some_id').snapshots().listen((docSnapshot) {
      if (docSnapshot.exists) {
        Map<String, dynamic> data = docSnapshot.data()!;
    
        // You can then retrieve the value from the Map like this:
        var name = data['name'];
      }
    });
    
    Run Code Online (Sandbox Code Playgroud)