firebase - 从firestore颤振提供程序中的db收集数据时如何初始化一个类
问题描述
我正在学习使用 Firestore 和 Flutter 提供程序的 Flutter Ecommerce 教程。
我想从 Firestore Db 中检索所有数据,但问题是我不知道如何初始化我将用于从 Db firestore 中检索数据的类。请帮忙。如果您有更好的方法,您可以与我分享您的知识。这是下面的代码:
import 'package:flutter/material.dart';
import 'package:shopping/db/product.dart';
import 'package:shopping/models/product.dart';
class AppProvider with ChangeNotifier {
List<Product>_fearturedProducts=[];
ProductService _productService=new ProductService();
AppProvider(){
//please how to initialize class AppProvider here
}
//getter
List<Product> get featuredProducts=>_fearturedProducts;
//method
void _getFeaturedProducts()async{
_fearturedProducts=await _productService.getFeaturedProducts();
notifyListeners();
}
}
ProductService 类的代码:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:shopping/models/product.dart';
class ProductService{
Firestore _firestore=Firestore.instance;
String collection="Products";
Future<List<Product>>getFeaturedProducts(){
_firestore.collection(collection).where('featured', isEqualTo:true).getDocuments()
.then((snap){
List<Product>featuredProducts=[];
snap.documents.map((snapshot)=> featuredProducts.add(Product.fromSnapshot(snapshot)));
return featuredProducts;
});
}
}
解决方案
我认为可能有很多解决方案,具体取决于您希望如何使用 AppProvider 类。
也许你可以这样做:
AppProvider(){
this._getFeaturedProducts();
}
比在你的主类中初始化对象,如:
AppProvider _appProvider = new AppProvider();
在对象创建期间,应从 firestore 获取数据,并通知所有侦听器。
我希望它会有所帮助!
推荐阅读
- python - 如何解决查找轮廓时产生的python openCV错误“没有足够的值来解包(预期3,得到2)”?
- java - 如何克服线程“主”java.util.InputMismatchException中的异常
- charts - 包含星期聚合的 Oracle Apex 条形图
- javascript - 用... JS 按字母顺序排列网格?CSS?
- python - 为什么重建损失函数乘以VAE中的常数?
- tensorflow - TensorFlow 支持的版本政策?
- google-merchant-center - 我想在 google 商家中心从 Content API v2 迁移到 v2.1,但我在庞大的文档中迷失了方向
- python - Django Paypal:如何从视图中取消订阅
- c++ - 解析 std::vector
带有 Boost.Program_options 的配置文件中的选项 - python - django {% url %} 模板循环