如何在Firebase Firestore Flutter中获取自动生成的文档ID?

时间:2019-12-17 07:14:31

标签: firebase flutter google-cloud-firestore

//这是我尝试的。 它不会返回添加的最新数据或最新数据。

Future getData() async {
    var now = new DateTime.now();
    var formatter = new DateFormat('yyyy-MM-dd');
    String formatted = formatter.format(now);
    final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
    final FirebaseUser user = await firebaseAuth.currentUser();
    final uid = user.uid;

    QuerySnapshot qn = await db
        .collection('exams')
        .document(uid)
        .collection('intellective speed test')
        .document('sensorimotor')
        .collection('$formatted')
        .where('createdAt', isLessThan: Timestamp.now().toDate().toString())
        .getDocuments();

    return qn.documents;
  }

1 个答案:

答案 0 :(得分:1)

您可以从DocumentSnapshot

获取每个文档ID。
for (int i = 0; i < querySnapshot.documents.length; i++) {
  DocumentSnapshot docSnap = querySnapshot.documents.elementAt(i);
  final id = docSnap.documentID;
}

querySnapshot.documents.forEach((docSnap) {
  final id = docSnap.documentID;
});