Flutter Navigator导航失效问题求助:点击登录按钮无法跳转至登录页面
嘿,我仔细扒了你的代码,终于找到问题根源了!问题出在复用组件RoundedButton的onPressed绑定逻辑上。
核心问题
你在newElevatedButton()方法里写的按钮点击事件是:
onPressed: () => onPressed,
这里只是把传入的onPressed函数对象返回出去,根本没有实际调用它!所以点击按钮时,导航逻辑完全没执行,自然没反应。
修复方案
把ElevatedButton的onPressed改成真正触发函数的写法,有两种简单方式:
- 直接调用函数:
onPressed: () => onPressed(),
- 更简洁的写法(推荐):直接传递函数引用,同时把参数类型改成更明确的
VoidCallback
修复后的完整RoundedButton代码:
class RoundedButton extends StatelessWidget { final String text; final VoidCallback onPressed; // 把Function换成VoidCallback,类型更安全 final Color color, textColor; const RoundedButton({ Key? key, required this.text, required this.onPressed, this.color = appPrimaryColour, this.textColor = Colors.white, }) : super(key: key); @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return Container( margin: const EdgeInsets.symmetric(vertical: 10), width: size.width * 0.8, child: ClipRRect( borderRadius: BorderRadius.circular(30), child: newElevatedButton(), ), ); } Widget newElevatedButton() { return ElevatedButton( child: Text( text, style: TextStyle(color: textColor), ), // 直接传递onPressed,不用额外包裹 onPressed: onPressed, style: ElevatedButton.styleFrom( primary: color, padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 20), textStyle: TextStyle( color: textColor, fontSize: 14, fontWeight: FontWeight.w500)), ); } }
额外确认项(可选)
- 检查
LoginPage是否在文件顶部正确导入,有没有拼写错误 - 确认
WelcomePage是在MaterialApp的子树中(你的代码里这部分是没问题的,只有在MaterialApp子树里的context才能调用Navigator)
改完之后,再点击WelcomePage的登录按钮,应该就能顺利跳转到LoginPage啦!
内容的提问来源于stack exchange,提问作者Katiso Koqo
相关产品推荐
相关产品推荐

