【问题标题】:Flutter/Firestore- Retrieving product information issueFlutter/Firestore-检索产品信息问题
【发布时间】:2020-10-15 18:30:40
【问题描述】:

我正在尝试从 Firestore 加载我的所有产品数据。我有一个数据架构:

class SingleProduct with ChangeNotifier {
  static const EVENT = "event";
  static const IMGURL = "imgUrl";
  static const NAME = "name";
  static const PRICE = "price";

//Private Variables
  String _event;
  String _imgUrl;
  String _name;
  double _price;

// getters
  String get event => _event;
  String get imgUrl => _imgUrl;
  String get name => _name;
  double get price => _price;


  SingleProduct.fromSnapshot(DocumentSnapshot snapshot) {
      _event = snapshot.data()[EVENT];
  _imgUrl = snapshot.data()[IMGURL];
  _name = snapshot.data()[NAME];
  _price = snapshot.data()[PRICE];}
  }
  

然后我创建了一个类来将收到的所有数据映射到产品列表:

class ProductServices {
  FirebaseFirestore _firestore = FirebaseFirestore.instance;

  String collection = 'products';

  Future<List<SingleProduct>> getAllProducts() async =>
      _firestore.collection(collection).get().then((snap) {
        print(snap.docs.length); // returns 11 products as expected
        List<SingleProduct> allProducts = [];
        snap.docs.map((snapshot) =>
            allProducts.add(SingleProduct.fromSnapshot(snapshot)));
        print(allProducts.length); //returns 0 so I think my map isn't working
        return allProducts;
      });
}

Firestore 查询按预期返回 11 个查询快照,但我随后尝试使用我的产品架构将它们添加到列表中,但结果显示该列表有 0 个元素。有什么建议如何将我的火基查询的结果映射到列表?

【问题讨论】:

  • 请编辑问题以解释究竟是什么不符合您的预期。我们真的不知道问题是什么。

标签: firebase flutter google-cloud-firestore


【解决方案1】:

使用forEach():

snap.docs.forEach((snapshot) => allProducts.add(SingleProduct.fromSnapshot(snapshot)));

解释时间: [tl;dr 你的 lambda 根本没有执行]

map() is a lazy function 用于转换列表中的元素,仅在要使用结果时才有效。

在您的代码中,map() 的结果在以后不再使用(例如,分配给变量),这就是为什么不调用其中的 lambda(如果不提前使用转换,为什么它会转换?)

另外,它不适合您的用例。

为了展示它的惰性,尝试在 DartPad 中运行这段代码:

void main() {
  List<String> list = ["a", "b", "c"];
  List<String> anotherList = [];
  var mappingOutput = list.map((element) { anotherList.add(element); return element + "X"; }).toList();
  print(list);
  print(mappingOutput);
  print(anotherList);
}

注意map() 的结果将被强制返回给一个变量,它把惰性推到一边并执行它。

anotherList 将被填写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 2021-06-28
    • 2023-04-09
    • 2023-04-07
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2020-10-25
    相关资源
    最近更新 更多