Flutter自定义可复用ElevatedButton:borderRadius设置与onPressed报错问题
问题1:onPressed属性报错修复
报错原因有两点:
- 声明的
onPressed参数为非空VoidCallback类型,但构造函数中没有加required关键字,Dart空安全校验不通过 - 内部
ElevatedButton的onPressed参数写死了空函数,没有透传外部传入的回调
修复方案: - 构造函数中给
onPressed增加required关键字,如果需要支持不传的场景,可将类型改为可空的VoidCallback? - 内部
ElevatedButton直接绑定传入的onPressed参数即可
问题2:borderRadius属性自定义配置修复
当前代码的shape属性写死了10px圆角,没有用到你定义的borderRadius入参,修复方案:
- 从传入的
borderRadius取值,未传时设置默认圆角兜底 - 直接将生成的
RoundedRectangleBorder赋值给shape属性即可
修复后完整代码
class CustomElevatedButton extends StatelessWidget { const CustomElevatedButton({ super.key, // 符合Flutter规范的默认参数 required this.child, this.backgroundColor, this.borderRadius, required this.onPressed, }); final Widget child; // 指定类型为Widget,避免动态类型隐患 final MaterialStateProperty<Color?>? backgroundColor; final BorderRadius? borderRadius; // 简化为直接传BorderRadius类型,降低使用成本 final VoidCallback onPressed; @override Widget build(BuildContext context) { return ElevatedButton( onPressed: onPressed, style: ButtonStyle( backgroundColor: backgroundColor, shape: MaterialStateProperty.all( RoundedRectangleBorder( // 优先用传入的圆角,否则兜底默认8px圆角,可自行调整默认值 borderRadius: borderRadius ?? BorderRadius.circular(8.0), ), ), ), child: child, ); } }
使用示例
// 基础用法,使用默认圆角 CustomElevatedButton( onPressed: () => print('登录按钮点击'), child: const Text('登录'), ) // 自定义圆角和背景色 CustomElevatedButton( onPressed: () => print('注册按钮点击'), borderRadius: BorderRadius.circular(16.0), backgroundColor: MaterialStateProperty.all(Colors.green), child: const Text('注册'), )
内容的提问来源于stack exchange,提问作者Jonnyfaz
相关产品推荐
相关产品推荐

