Reputation: 77
I am following one tutorial on Flutter Ecommerce using Firestore and flutter provider.
I wanted to retrieve all the data from firestore Db, but the problem is I don't know how to initialize the class I am going to use to retrieve data from Db firestore. Pls help. And if you have better approaches you can share your knowledge with me. this is the code below:
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();
}
}
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;
});
}
}
Upvotes: 0
Views: 1082
Reputation: 4262
I think that there may be many solution depending how you want to use AppProvider class.
Maybe you can do it like:
AppProvider(){
this._getFeaturedProducts();
}
Than in your main class init the object like:
AppProvider _appProvider = new AppProvider();
During object creation the data should be taken from firestore and all listeners will be notified.
I hope it will help!
Upvotes: 1