首页 > 解决方案 > 从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;
 }); 

}

}

标签: firebasefluttergoogle-cloud-firestoreflutter-provider

解决方案


我认为可能有很多解决方案,具体取决于您希望如何使用 AppProvider 类。

也许你可以这样做:

AppProvider(){
    this._getFeaturedProducts();
  }

比在你的主类中初始化对象,如:

AppProvider _appProvider = new AppProvider();

在对象创建期间,应从 firestore 获取数据,并通知所有侦听器。

我希望它会有所帮助!


推荐阅读