Reputation: 11
Hello I'm new to flutter and wanted to create a recipe app but I can't seem to be able to retrieve recipe data from firebase to my app.
This is the recipe model that I created .
import 'package:cloud_firestore/cloud_firestore.dart';
class RecipeModel {
late String fid;
late String name;
late String category;
late String imgUrl;
late String duration;
List ingredients = [];
List preparation = [];
RecipeModel.fromMap(Map<String, dynamic> data){
fid = data['fid'];
name = data['name'];
category = data['category'];
duration = data['duration'];
imgUrl = data['imgUrl'];
ingredients = data['ingredients'];
preparation = data['preparation'];
}
}
I want to display all the recipes in this screen in list view. I tried different methods but it didn't work.
class AllRecipeScreen extends StatefulWidget {
@override
_AllRecipeScreenState createState() => _AllRecipeScreenState();
}
class _AllRecipeScreenState extends State<AllRecipeScreen>{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView.separated(
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Image.asset(
ToolsUtilities.imageRecipe[index],
width: 120,
fit: BoxFit.fitWidth,
),
title: Text("Recipe Name"),
subtitle: Text("Category"),
// onTap: () {
// foodNotifier.currentRecipe = foodNotifier.recipelist[index];
// Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){
// return FoodDetail();
// }));
// },
);
},
itemCount: ToolsUtilities.imageRecipe.length,
separatorBuilder: (BuildContext context, int index){
return Divider(
color: Colors.black,
);
},
),
);
}
}
This is my firebase and recipe collection:
Upvotes: 1
Views: 194
Reputation: 9
First get a reference to your collection as a field in your StatefulComponent:
final Stream<QuerySnapshot<Map<String, dynamic>>> _myStream = FirebaseFirestore.instance
.collection('recipes')
.snapshots();
Once you got it create a StreamBuilder
component passing the collection as a stream and using it within a builder:
child: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: _myStream,
builder: (context, snapshot) {
//your code goes here
}
)
To use it you have to:
So the code looks like this:
child: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: _myStream,
builder: (context, snapshot) {
if (snapshot.hasError) { //check for errors
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) { //connection is still being set up
return const CircularProgressIndicator();
}
if (snapshot.hasData) { // wait for data
return const CircularProgressIndicator();
}
var data = snapshot.data!.docs.map((document) {
return RecipeModel.fromMap(document);
}).toList();
return ListView(
//ListView code
)
}
)
Upvotes: 1