如何从flutter中使用Firestore中的唯一文档id进行查询



我有多个文档,其中包含不同的工作人员名称及其详细信息,我没有给出auto,而是为每个文档分配了一个唯一的id,如"id_1"、"id_2"等。现在,我的问题是如何访问这些不同的文档及其特定字段,如工作人员姓名和地址,并使用文本小部件进行显示。

如果你想一次获取所有文档,那么你可以使用:

StreamBuilder<QuerySnapshot>(
  stream: Firestore().collection('Workers').snapshots(),
  builder: (context, snapshot) {
    if (snapshot.data != null) {
      // Here u will get list of document snapshots
      final List<DocumentSnapshot> documents = snapshot.data.documents;
      // now u can access each document by simply specifying its number
      // u can also use list view to display every one of them
      return ListView.builder(
        itemCount: documents.length,
        itemBuilder: (context, int index) => Text(documents[index].data['name']),
      );
    } else {
      // Show loading indicator here
    }
  },
);

如果你想获得特定的文档详细信息(如果你有文档id(,那么你可以使用:

Future<DocumentSnapshot> _getDocument(String documentName) async {
   return await Firestore().collection('Workers').document(documentName).get();
 }

现在你可以通过那里的名称访问字段,例如

documentSnapshot.data['Name']

我希望这能有所帮助:(

您可以使用获取文档快照

DocumentSnapshot documentSnapshot = await Firestore.instance.collection('yourCollection').document('docId').get();

你只需调用就可以访问它

documentSnapshot.data['yourField'];

最新更新