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

Flutter中实现点击ListView列表项跳转至对应页面的方法

实现ListView列表项点击跳转至对应页面(Flutter)

步骤1:优化数据模型,新增路由字段

为了避免在点击事件中写大量字符串判断,直接给HomeModel添加路由字段,让每个列表项和目标页面路由一一对应,同时修正原模型中tittle的拼写错误:

class HomeModel {
  late String title;
  late String icon;
  late String route; // 新增路由关联字段

  HomeModel(
    this.title,
    this.icon,
    this.route,
  );
}

步骤2:更新数据列表,绑定对应路由

给每个列表项配置好Routes中定义的路由路径:

final List<HomeModel> homes = [
  HomeModel("Agentes", "assets/icons/agents_icon.png", Routes.agents),
  HomeModel("Armas", "assets/icons/weapons_icon.png", Routes.weapons),
  HomeModel("Mapas", "assets/icons/maps_icon.png", Routes.maps),
  HomeModel("Ranks", "assets/icons/ranks_icon.png", Routes.ranks),
  HomeModel("Cards", "assets/icons/cards_icon.png", Routes.cards),
];

步骤3:修改ListView布局,添加点击跳转逻辑

用InkWell包裹列表项容器(自带Material点击波纹反馈,比GestureDetector体验更好),并在onTap事件中调用Navigator.pushNamed完成路由跳转:

Expanded(
  child: ListView(
    children: [
      for (var home in homes)
        InkWell(
          onTap: () {
            // 点击时跳转到对应路由页面
            Navigator.pushNamed(context, home.route);
          },
          child: Container(
            margin: const EdgeInsets.fromLTRB(10, 15, 10, 5),
            padding: const EdgeInsets.fromLTRB(30, 5, 15, 5),
            width: double.infinity,
            decoration: BoxDecoration(
              border: Border.all(
                color: const Color.fromARGB(255, 255, 70, 85),
                width: 2,
              ),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  margin: const EdgeInsets.fromLTRB(0, 1, 38, 0),
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Text(
                        home.title,
                        style: GoogleFonts.bowlbyOneSc(
                          color: Colors.white,
                          letterSpacing: .5,
                          fontSize: 24,
                        ),
                      ),
                    ],
                  ),
                ),
                const Spacer(),
                Container(
                  width: 125,
                  height: 140,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Image.asset(home.icon),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
    ],
  ),
),

额外说明

  • 这种通过数据模型绑定路由的方式,避免了冗余的条件判断,代码更简洁易维护;
  • 若不需要波纹反馈,可将InkWell替换为GestureDetector,逻辑完全一致。

内容的提问来源于stack exchange,提问作者Mikael David

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:25:15