简体   繁体   English

如何使用 flutter 从 firebase 中检索数据

[英]How to retrieve data from firebase using flutter

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.您好,我是 flutter 的新手,想创建一个食谱应用程序,但我似乎无法将食谱数据从 firebase 检索到我的应用程序。

This is the recipe model that I created.这是我创建的食谱 model。

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:这是我的firebase和菜谱合集:

First get a reference to your collection as a field in your StatefulComponent:首先获取对集合的引用,作为 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:一旦你得到它,创建一个StreamBuilder组件将集合作为 stream 传递并在构建器中使用它:

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
        )

    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过 flutter 中的文档从 firebase 存储中检索数据? - How do i retrieve data from firebase store by document in flutter? 如何从flutter中的firebase取回email的ID? - How to retrieve the email ID from firebase in flutter? 如何使用 flutter 和 dart 从 Cloud Firestore 检索特定数据? - how to retrieve specific data from Cloud Firestore using flutter and dart? 如何从 flutter 中的 firebase 中的多个文档中检索整个嵌套数据 - How to retrieve whole nested data form multiple document from firebase in flutter 如何使用 flutter 中的子值从 firebase 获取数据? - How to get data from firebase using child value in flutter? 如何使用 Flutter/Dart 从 Firebase 实时数据库中读取数据 - How to read data from Firebase Realtime database using Flutter/Dart 如何在没有 EventListener 的情况下从 Firebase 检索数据? - How to retrieve data from Firebase without EventListener? 使用 flutter 从 firebase Firestore 获取数据 - fetching data from firebase firestore using flutter 如何使用 where 子句从 firebase 正确获取数据,并使用 flutter 从 firebase 中正确获取数据 - How to correctly fetch data from firebase using where clauses and custom filters from firebase using flutter 如何从 Firebase 检索其他活动的数据? - How to retrieve data from Firebase on other activity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM