dart Flutter在firebase中检索子子集合中的所有文档

4sup72z8  于 2023-02-14  发布在  Flutter
关注(0)|答案(1)|浏览(115)

我的嵌套集合看起来像这样:

User--> drugs--> drugsTime

我想检索特定药物的子子集合(drugsTime)中的所有文档,但我不知道药物文档ID,因此我执行了以下操作:

getData() async {
    final User? user = FirebaseAuth.instance.currentUser;
    final _uid = user?.uid;
    var drugID = "";
    final QuerySnapshot<Map<String, dynamic>> querySnapshot =
    await FirebaseFirestore.instance
        .collection("users")
        .doc(_uid)
        .collection('drug')
        .where("drugName", isEqualTo: widget.title)
        .get();
    querySnapshot.docs.forEach((element) async {
      drugID = element.id;
    });
    final QuerySnapshot<Map<String, dynamic>> querySnapshot2  = (await FirebaseFirestore.instance
        .collection("users")
        .doc(_uid)
        .collection("drug")
        .doc(drugID)
        .get()) as QuerySnapshot<Map<String, dynamic>>;
    querySnapshot2.docs.forEach((element) async {
      drugTime .add (element.get('time'));
      isTaken.add(element.get("isTaken"));
    });

    print(drugTime);
    print(isTaken);
  }

但出现此错误:

E/flutter (24517): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_JsonDocumentSnapshot' is not a subtype of type 'QuerySnapshot<Map<String, dynamic>>' in type cast
E/flutter (24517): #0      _historyState.getData (package:taafi_application_v1/pages/history.dart:38:17)
E/flutter (24517): <asynchronous suspension>

问题表现在

as QuerySnapshot<Map<String, dynamic>>;

我该怎么解决呢?

utugiqy6

utugiqy61#

在这里,我们用QuerySnapshot强制转换DocumentSnapshotwhere将返回QuerySnapshotdoc将返回DocumentSnapshot
方法getData的代码应如下所示

getData() async {
  final User? user = FirebaseAuth.instance.currentUser;
  final _uid = user?.uid;
  var drugID = "";
  final QuerySnapshot<Map<String, dynamic>> querySnapshot =
  await FirebaseFirestore.instance
      .collection("users")
      .doc(_uid)
      .collection('drug')
      .where("drugName", isEqualTo: widget.title)
      .get();
  querySnapshot.docs.forEach((element) async {
    drugID = element.id;
  });
  final DocumentSnapshot<Map<String, dynamic>> doc  = await FirebaseFirestore.instance
      .collection("users")
      .doc(_uid)
      .collection("drug")
      .doc(drugID)
      .get();
  drugTime.add (doc.data()!['time']);//Make sure time has value
  isTaken.add(doc.data()!['isTaken']);

  print(drugTime);
  print(isTaken);
}

请确定您是被要求的。

相关问题