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

基于Switch Case实现Flutter ListView列表项的页面导航

解决ListView列表项跳转对应页面的问题

方案:通过Switch Case实现精准页面跳转

你可以通过编写一个根据列表项ID(或索引)返回对应页面的函数,再结合ListView的点击事件来实现需求,具体步骤如下:


1. 编写页面匹配函数

创建一个函数,接收列表项的ID,用switch case返回对应的目标页面组件:

Widget _getTargetScreen(int itemId) {
  switch(itemId) {
    case 1:
      return DepositScreen(); // 注意Dart类名需首字母大写,按规范调整你的页面类名
    case 2:
      return SecondPage();
    case 3:
      return ThirdPage();
    // 依次补充id从4到20的case,对应你所有的目标页面
    default:
      return Scaffold(body: Center(child: Text("未找到对应页面"))); // 兜底页面,避免崩溃
  }
}

2. 修正ListView并绑定跳转逻辑

调整你原来的ListView.builder代码(修复语法问题),并在ListTile的onTap事件中调用上述函数:

ListView.builder(
  itemCount: _av_searched_listiles.length,
  itemBuilder: (context, index) {
    final currentItem = _av_searched_listiles[index];
    return Card(
      borderOnForeground: true,
      elevation: 8,
      child: Container(
        height: 44.h,
        child: ListTile(
          title: Text(currentItem["name"]), // 可选:显示列表项名称
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => _getTargetScreen(currentItem["id"]),
              ),
            );
          },
        ),
      ),
    );
  },
)

额外提示

  • 建议用列表项的id而非index作为判断条件,避免列表排序、过滤后索引和页面不匹配的问题
  • 严格遵循Dart命名规范:页面类名首字母大写(比如deposit_screen改为DepositScreen)
  • 务必补充完所有20个case的页面映射,default分支可以处理异常情况,防止程序崩溃

内容的提问来源于stack exchange,提问作者Pravin Suthar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:35:26