Flutter报错:命名参数'onPressed'未定义,登录按钮失效如何解决?
解决Flutter中“The named parameter 'onPressed' isn't defined”错误
问题原因
你把onPressed参数直接添加到了Container组件上,但Container本身并没有onPressed这个命名参数,这就是报错的核心原因。
解决方案
有两种常用的修正方式,根据你的需求选择:
方式1:使用原生按钮组件(推荐)
直接用Flutter提供的ElevatedButton(或TextButton、OutlinedButton)替代Container,这类按钮组件原生支持onPressed回调,还能自动处理按钮的点击状态:
// 替换原来的Container部分 ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.pink[400], // 设置按钮背景色 padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 16), // 调整内边距优化点击区域 ), onPressed: () async { // 这里编写登录逻辑,例如调用_auth.signInWithEmailAndPassword(email, password) }, child: const Text( 'Sign in', style: TextStyle(color: Colors.white), ), )
方式2:用GestureDetector包裹Container
如果一定要保留Container的自定义样式,可以用GestureDetector把它包裹起来,通过onTap实现点击事件:
// 替换原来的Container部分 GestureDetector( onTap: () async { // 登录逻辑写在这里 }, child: Container( padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 16), // 增加内边距让点击区域更合理 color: Colors.pink[400], child: const Text( 'Sign in', style: TextStyle(color: Colors.white), ), ), )
额外注意事项
你的代码还有几处小问题需要修正,避免后续报错:
- 两个
TextFormField的末尾都缺少逗号,需要补上 - 代码未完全闭合,
Form、Column、Scaffold等组件的括号都没写完,要补充完整
内容的提问来源于stack exchange,提问作者Vuyani James Dasheka
相关产品推荐
相关产品推荐

