我无法使用 flutter 从 firebase 数据库获取文档

问题描述 投票:0回答:1

我在 firebase 中有一个名为“类别”的集合,在这个集合下我有我想要获取的文档。我定义了方法“getAllCategories”,该方法应该从数据库获取类别:

final _db = FirebaseFirestore.instance;
  Future<List<CategoryModel>> getAllCategories() async {
    try {
      final snapshot = await _db.collection('Categories').get();
      final list =
          snapshot.docs.map((e) => CategoryModel.fromSnapshot(e)).toList();
      print("${list}");
      return list;
    } on FirebaseException catch (e) {
      throw TFirebaseException(e.code).message;
    } on PlatformException catch (e) {
      throw TPlatformException(e.code).message;
    } catch (e) {
      throw 'Something went wrong.Please try again';
    }
  }

然后我在“fetchCategories”函数中调用了这个函数:

Future<void> fetchCategories() async {
    try {
      isLoading.value = true;

      final Categories = await _categoryRepository.getAllCategories();
      allCategories.assignAll(Categories);
      featuredCategories.assignAll(allCategories
          .where((category) => category.isFeatured && category.parentId.isEmpty)
          .take(8)
          .toList());
    } catch (e) {
      TLoader.errorSnackBar(
          title: 'Oh Snap mochkla fl caregori', message: e.toString());
    } finally {
      isLoading.value = false;
    }
  }
lass CategoryModel {
  String id;
  String name;
  String image;
  String parentId;
  bool isFeatured;
  CategoryModel(
      {required this.id,
      required this.name,
      required this.image,
      required this.isFeatured,
      this.parentId = ''});

这是类别模型:

没有错误,但在我做了一些测试之后,我发现该方法不起作用是 getAllCategories 函数。如果有人能给出这个问题的可能原因,他会节省我的时间

flutter firebase dart google-cloud-firestore fetch
1个回答
0
投票

请确保

  1. 收藏不为空
  2. firestore 安全规则已正确配置
  3. 收藏名称正确

此外,您还可以使用断点或打印语句来调试数据。

您可以像下面这样修改代码

Future<List<CategoryModel>> getAllCategories() async {
  try {
    final snapshot = await _db.collection('Categories').get();
    if (snapshot.docs.length == 0) {
      print("No documents found in Categories collection");
      return []; // Return empty list if no documents
    }

    final list = snapshot.docs.map((e) => CategoryModel.fromSnapshot(e)).toList();
    print("Fetched categories: ${list}"); // Print fetched categories
    return list;
  } on FirebaseException catch (e) {
    throw TFirebaseException(e.code).message;
  } on PlatformException catch (e) {
    throw TPlatformException(e.code).message;
  } catch (e) {
    throw 'Something went wrong. Please try again';
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.