【发布时间】: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