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

Flutter中GridView的每个元素如何导航到对应指定页面?

你当前代码的问题是gridItem方法的onTap回调中硬编码了跳转目标为Page1,所以无论点击哪个列表项,都会跳转到Page1页面。可以通过以下两种方案解决:


方案1:通过Category的name字段判断跳转(快速实现)

直接修改gridItem方法中onTap的逻辑,根据传入的category的name值匹配对应跳转页面即可:

InkWell gridItem(Category category) {
  return InkWell(
    child: Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 100,
            height: 100,
            padding: const EdgeInsets.all(8),
            child: Image.asset(category.image),
          ),
          Text(
            category.name,
            style: const TextStyle(fontSize: 18),
          ),
        ],
      ),
    ),
    onTap: () {
      Widget targetPage;
      // 此处的字符串要和你初始化Category时传入的name参数完全一致
      switch(category.name) {
        case 'page1':
          targetPage = const Page1();
          break;
        case 'page2':
          targetPage = const Page2();
          break;
        default:
          // 可自定义默认跳转页面,比如返回首页
          targetPage = const HomePage();
      }
      Navigator.push(context, MaterialPageRoute(builder: (context) => targetPage));
    },
  );
}

方案2:扩展Category类绑定跳转页面(更易维护)

如果后续要加更多页面项,推荐给Category类新增页面构造器属性,避免硬编码字符串判断,后续新增项无需修改gridItem逻辑:

  1. 先修改Category类定义:
class Category {
  final String name;
  final String image;
  // 新增跳转页面的构造器属性
  final Widget Function() targetPage;

  Category({
    required this.name,
    required this.image,
    required this.targetPage,
  });
}
  1. 初始化Category列表时绑定对应页面:
// 示例列表初始化代码,替换为你自己的资源路径即可
final List<Category> categoryList = [
  Category(
    name: 'page1',
    image: 'assets/images/page1_icon.png',
    targetPage: () => const Page1(),
  ),
  Category(
    name: 'page2',
    image: 'assets/images/page2_icon.png',
    targetPage: () => const Page2(),
  ),
];
  1. 最后修改gridItem的onTap逻辑:
onTap: () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => category.targetPage()),
  );
},

内容的提问来源于stack exchange,提问作者Abdullah Bahattab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:36:03