Flutter提取重复布局为方法后,TextButton导航功能异常求助
你的导航逻辑失效的核心原因是错误地用字符串参数尝试动态创建页面实例——Dart不支持$sport_screen()这种通过字符串插值生成类实例的写法。
修复步骤:
- 修改方法参数类型:将
String sport_screen替换为Widget Function()类型,直接接收一个返回目标页面Widget的函数 - 调整导航代码:直接调用传入的函数生成页面实例
修复后的完整代码:
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
相关产品推荐
相关产品推荐

