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

Flutter提取重复布局为方法后,TextButton导航功能异常求助

Flutter TextButton导航失效问题解决方法

你的导航逻辑失效的核心原因是错误地用字符串参数尝试动态创建页面实例——Dart不支持$sport_screen()这种通过字符串插值生成类实例的写法。

修复步骤:

  1. 修改方法参数类型:将String sport_screen替换为Widget Function()类型,直接接收一个返回目标页面Widget的函数
  2. 调整导航代码:直接调用传入的函数生成页面实例

修复后的完整代码:

TextButton buildSportSection(Widget Function() sportScreen, String sportName, String name) {
  return TextButton(
    onPressed: () {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => sportScreen(),
        ),
      );
    },
    child: Container(
      height: 100,
      decoration: BoxDecoration(
        color: Color(0xFFF7F8F8),
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.only(
          bottomRight: Radius.circular(50),
          topRight: Radius.circular(50),
        ),
      ),
      child: Row(
        children: [
          Image.asset('assets/images/$name.png'),
          Text(sportName, style: GoogleFonts.abhayaLibre(fontSize: 20))
        ],
      ),
    ),
  );
}

调用示例:

当你需要生成对应页面的按钮时,直接传入页面的构造函数:

// 假设目标页面是FootballScreen
buildSportSection(() => FootballScreen(), "足球", "football")

额外说明:

  • 确保目标页面类是继承自StatelessWidget/StatefulWidget的合法Widget
  • 确认已经正确导入了目标页面的文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:35:06