使 Stream 能够从 Cloud Firestore Flutter 获取数据

发布于 2025-01-13 08:48:00 字数 1022 浏览 3 评论 0原文

我想从我的 Cloud Firestore 数据库集合中获取数据。我尝试使用流,但似乎它不起作用,因为我无法在控制台上打印这些数据并在屏幕上获取它们。我做错了什么吗?

Stream<List<ProductModel>> getAllProducts() =>
      firebaseFirestore.collection("products").snapshots().map((query) =>
          query.docs.map((item) => ProductModel.fromMap(item.data())).toList());

如果您想知道,这是我的 ProductModel 类,其中包含与我的 firestore 集合相同的属性

class ProductModel {
  static const ID = "id";
  static const IMAGE = "image";
  static const NAME = "name";
  static const BRAND = "brand";
  static const PRICE = "price";

  String? id;
  String? image;
  String? name;
  String? brand;
  double? price;

  ProductModel(
      {required this.id,
      required this.image,
      required this.name,
      required this.brand,
      required this.price});

  ProductModel.fromMap(Map<String, dynamic> data) {
    id = data[ID];
    image = data[IMAGE];
    name = data[NAME];
    brand = data[BRAND];
    price = data[PRICE].toDouble();
  }
}

I want to get datas from a collection of my cloud firestore database. I tried with a stream but it seems that it doesn't work as I'm unable to print those datas on the console and to fetch them on screen. Did I do something wrong?

Stream<List<ProductModel>> getAllProducts() =>
      firebaseFirestore.collection("products").snapshots().map((query) =>
          query.docs.map((item) => ProductModel.fromMap(item.data())).toList());

In case you want to know, Here is my ProductModel class, which contains the same properties asmy firestore collection

class ProductModel {
  static const ID = "id";
  static const IMAGE = "image";
  static const NAME = "name";
  static const BRAND = "brand";
  static const PRICE = "price";

  String? id;
  String? image;
  String? name;
  String? brand;
  double? price;

  ProductModel(
      {required this.id,
      required this.image,
      required this.name,
      required this.brand,
      required this.price});

  ProductModel.fromMap(Map<String, dynamic> data) {
    id = data[ID];
    image = data[IMAGE];
    name = data[NAME];
    brand = data[BRAND];
    price = data[PRICE].toDouble();
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文