You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter ListView点击不同列表项跳转至不同独立页面的实现问题

解决Flutter ListView点击条目跳转不同独立页面的方案

你可以通过建立条目标识和目标页面的映射关系来实现需求,不需要复用同一个页面渲染不同数据,完全支持每个跳转目标是独立结构的页面,具体修改如下:

1. 定义页面映射表

在_DashboardScreenState类中提前声明条目和对应页面的映射关系,这里用FOOD_DATA中每个条目的唯一字段(比如名称name、或者id)作为key,value为你已经开发好的独立页面实例:

class _DashboardScreenState extends State<DashboardScreen> {
  // 新增:页面映射配置,依次添加所有条目对应的独立页面
  final Map<String, Widget> itemPageMap = {
    "第一个条目的name值": const APage(),
    "第二个条目的name值": const CPage(),
    "第三个条目的name值": const TPage(),
    // 剩余条目按照格式依次添加即可
  };

  // 原有代码保持不变
  final CategoriesScroller categoriesScroller = CategoriesScroller();
  ScrollController controller = ScrollController();
  bool closeTopContainer = false;
  double topContainer = 0;
  List<Widget> itemsData = [];

2. 修改点击跳转逻辑

找到你getPostsData方法里GestureDetector的onTap回调,替换为根据当前点击的条目匹配映射表跳转的逻辑:

responseList.forEach((post) {
  listItems.add(GestureDetector(
    // 替换原有onTap逻辑
    onTap: () {
      final targetPage = itemPageMap[post["name"]];
      if (targetPage != null) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => targetPage),
        );
      }
    },
    child: Container(
      // 原有Container的代码完全保持不变
      height: 150,
      margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20.0)), color: Colors.white, boxShadow: [
        BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
      ]),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  post["name"],
                  style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                SizedBox(
                  height: 10,
                )
              ],
            ),
            Image.asset(
              "assets/images/${post["image"]}",
              height: double.infinity,
            )
          ],
        ),
      ),
    ),
  ));
});

补充说明

  • 如果你的FOOD_DATA里有唯一id字段,建议用id作为映射表的key,比用name更稳妥,不会出现重名匹配错误的问题
  • 如果独立页面需要接收当前条目的部分数据,直接在创建页面实例时传参即可,比如APage(postData: post)
  • 页面实际效果参考:
    页面实际效果图

内容的提问来源于stack exchange,提问作者Muhammad Haseeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:18:03