1

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:

1 Answer 1

1

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:

  • make sure that there is any data
  • make sure there were no errors

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
        )

    }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.