如何通过StreamBuilder将Firestore的QuerySnapshot转模型列表并在ListView加载
实现步骤
首先在你的页面 Widget 中完成如下代码编写即可实现需求:
- 先实例化你封装好的 Database 类(如果你的 Database 构造需要传参数,比如用户 uid 等,自行对应传入即可)
final Database db = Database();
- 在 Widget 的 build 方法中插入 StreamBuilder 组件,关联你写的
recipeData流,内部嵌套 ListView.builder 渲染列表:
@override Widget build(BuildContext context) { return Scaffold( // 你自己的页面其他配置,比如appBar之类的保留即可 body: StreamBuilder<List<RecipeData>>( stream: db.recipeData, builder: (context, snapshot) { // 加载状态处理 if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } // 错误状态处理 if (snapshot.hasError) { return Center(child: Text('加载食谱失败:${snapshot.error.toString()}')); } // 拿到数据后的处理 final recipeList = snapshot.data ?? []; // 数据为空的情况 if (recipeList.isEmpty) { return const Center(child: Text('暂无食谱数据')); } // 渲染列表 return ListView.builder( padding: const EdgeInsets.all(16), itemCount: recipeList.length, itemBuilder: (context, index) { final recipe = recipeList[index]; // 这里替换成你自己的列表项UI即可 return ListTile( leading: Image.network(recipe.imgPath), title: Text(recipe.recipeTitle), subtitle: Text('烹饪时长:${recipe.cookingTime}分钟 | 份量:${recipe.servings}人份'), // 你可以自己加点击事件等其他逻辑 ); }, ); }, ), ); }
可选优化建议
你现有的 getRecipes 方法可以补充类型转换,适配空安全规则避免编译警告:
List<RecipeData> getRecipes(QuerySnapshot snapshot) { return snapshot.docs.map((doc) { // 新增类型强转,避免隐式类型异常 final data = doc.data() as Map<String, dynamic>; return RecipeData( recipeTitle: data[kRecipeTitle], cookingTime: data[kCookingTime], imgPath: data[kRecipeImage], ingredients: data[kIngredients], preparation: data[kPreparation], numOfLikes: data[kNumOfLikes], publishedDate: data[kPublishedDate], servings: data[kServings], recipeCat: data[kRecipeCat], recipeId: doc.id, ); }).toList(); }
内容的提问来源于stack exchange,提问作者Mohammed Nadim
相关产品推荐
相关产品推荐

