Flutter开发:点击食品名称展示匹配关联的制作说明
实现食品详情页匹配展示制作说明的解决方案
问题背景
已完成主页面的食品名称列表展示,点击食品名称后,需要在详情页根据food中batter的id与instruction的category匹配,展示对应的制作说明内容。
解决方案步骤
1. 修正主页面资源路径错误
先修正主页面getList方法里的资源路径拼写错误:
final getResponse = await rootBundle.loadString('assets/post.json'); // 把assest改为assets
2. 修改主页面跳转逻辑,传递完整指令数据
在主页面的GestureDetector回调中,除当前Food对象外,同时传递所有instruction数据给详情页:
onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => FoodDetail( food: word, instructions: snapshot.data!.instruction, ), ), ); },
3. 实现FoodDetail详情页组件
创建FoodDetail页面,接收参数后筛选匹配的指令并展示:
import 'package:flutter/material.dart'; import '../model/post.dart'; class FoodDetail extends StatelessWidget { final Food food; final List<Instruction>? instructions; const FoodDetail({ Key? key, required this.food, required this.instructions, }) : super(key: key); @override Widget build(BuildContext context) { // 获取当前食品对应的面糊ID String? batterId = food.description?.batter?.first.id; // 筛选匹配的制作说明 List<Instruction> matchedInstructions = []; if (batterId != null && instructions != null) { matchedInstructions = instructions! .where((instr) => instr.category == batterId) .toList(); } return Scaffold( appBar: AppBar(title: Text(food.name ?? '食品详情')), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 食品名称 Text( food.name ?? '未知食品', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), const SizedBox(height: 16), // 面糊类型 Text('面糊类型: ${food.description?.batter?.first.type ?? '未知'}'), const SizedBox(height: 24), // 制作说明标题 const Text( '制作说明:', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500), ), const SizedBox(height: 8), // 匹配的说明列表 if (matchedInstructions.isNotEmpty) Expanded( child: ListView.builder( itemCount: matchedInstructions.length, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4.0), child: Text( '${index + 1}. ${matchedInstructions[index].content ?? ''}', style: const TextStyle(fontSize: 16), ), ); }, ), ) else const Text('暂无制作说明'), ], ), ), ); } }
代码说明
- 通过
food.description?.batter?.first.id获取当前食品对应的面糊ID - 使用
where方法筛选出category与面糊ID匹配的所有制作说明 - 页面布局先展示食品基础信息,再列出匹配的说明内容,无数据时显示提示文本
内容的提问来源于stack exchange,提问作者Joven Dev
相关产品推荐
相关产品推荐

