【问题标题】:how to initialize a class when collecting data from db in firestore flutter provider从firestore颤振提供程序中的db收集数据时如何初始化一个类
【发布时间】:2020-06-08 01:25:14
【问题描述】:

我正在学习使用 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;
 }); 

}

}

【问题讨论】:

  • 请问你想用这个构造函数实现什么?为什么不能是无参构造函数?
  • 我想在 main.dart 中使用 changenotifier 来调用它
  • 类似这样的“ChangeNotifierProvider.value(value: UserProvider.initialize()),”如果我有另一个 changenotifier,我也会使用多提供者
  • 你想在这个 AppProvider 类中调用它吗?
  • 在 main.dart 但我不知道我将为构造函数提供的参数

标签: firebase flutter google-cloud-firestore flutter-provider


【解决方案1】:

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

也许你可以这样做:

AppProvider(){
    this._getFeaturedProducts();
  }

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

AppProvider _appProvider = new AppProvider();

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

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2020-05-15
    • 1970-01-01
    • 2019-10-24
    • 2022-01-21
    • 2021-12-13
    • 2020-12-10
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多