我如何从 Firestore 中检索每个文档的文档 ID
how can i retrieve document id of each document from Firestore in flutter
这里有我从 Firebase 检索所有文档的代码,我只能检索文档中存在的数据,但我也想用它检索文档 ID,我该怎么做?
StreamBuilder<QuerySnapshot>(
stream: getData(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return new ListView(
children: snapshot.data.documents
.map((DocumentSnapshot document) {
return new CustomCard(
name: document['name'],
phone: document['phno'],
service: document['Category'],
address: document['address'],
pin: document['pin'],
payment: document['Payment'],
);
}).toList(),
);
}
},
),
这是我的getter函数
Stream<QuerySnapshot> getData()async*{
FirebaseUser user = await FirebaseAuth.instance.currentUser();
yield* Firestore.instance
.collection('User')
.where("userId", isEqualTo: user.uid)
.orderBy('upload time', descending: true)
.snapshots();
}
要获取 ID,请执行以下操作:
.map((DocumentSnapshot document) {
return new CustomCard(
docId : document.documentID,
name: document['name'],
phone: document['phno'],
service: document['Category'],
address: document['address'],
pin: document['pin'],
payment: document['Payment'],
);
}).toList(),
documentID
将为您提供每个文档 ID。
你也可以这样做
snapshot.data!.docs[index].id
这将 return 该索引处的文档 ID
这里有我从 Firebase 检索所有文档的代码,我只能检索文档中存在的数据,但我也想用它检索文档 ID,我该怎么做?
StreamBuilder<QuerySnapshot>(
stream: getData(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return new ListView(
children: snapshot.data.documents
.map((DocumentSnapshot document) {
return new CustomCard(
name: document['name'],
phone: document['phno'],
service: document['Category'],
address: document['address'],
pin: document['pin'],
payment: document['Payment'],
);
}).toList(),
);
}
},
),
这是我的getter函数
Stream<QuerySnapshot> getData()async*{
FirebaseUser user = await FirebaseAuth.instance.currentUser();
yield* Firestore.instance
.collection('User')
.where("userId", isEqualTo: user.uid)
.orderBy('upload time', descending: true)
.snapshots();
}
要获取 ID,请执行以下操作:
.map((DocumentSnapshot document) {
return new CustomCard(
docId : document.documentID,
name: document['name'],
phone: document['phno'],
service: document['Category'],
address: document['address'],
pin: document['pin'],
payment: document['Payment'],
);
}).toList(),
documentID
将为您提供每个文档 ID。
你也可以这样做
snapshot.data!.docs[index].id
这将 return 该索引处的文档 ID