Flutter如何使用ButtonStyle实现可变色的圆角ElevatedButton?
解决方案
仅用ElevatedButton.styleFrom实现全部需求
ElevatedButton.styleFrom的样式参数本身支持传入MaterialStateProperty类型的动态状态值,你可以直接在同一个方法内完成圆角、尺寸配置和按下变色逻辑:
style: ElevatedButton.styleFrom( // 配置尺寸 fixedSize: const Size(200, 50), // 固定宽高,也可替换为minimumSize适配内容 // 配置圆角 shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), // 配置按下变色逻辑 backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Colors.black; } return Colors.red; }), // 其他样式如padding、阴影色等都可以在此处添加 )
合并两种样式配置的方案
如果你已经写好了独立的ButtonStyle配置,也可以通过copyWith方法将styleFrom生成的静态样式和动态状态样式合并:
style: ElevatedButton.styleFrom( fixedSize: const Size(200, 50), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), // 用copyWith覆盖动态背景色配置 ).copyWith( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Colors.black; } return Colors.red; }), )
直接在原生ButtonStyle中配置尺寸、圆角
你之前用的原生ButtonStyle也支持配置圆角和尺寸,只需要给对应属性套上MaterialStateProperty.all即可:
style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return Colors.black; } return Colors.red; }), // 配置圆角 shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), ), // 配置尺寸 fixedSize: MaterialStateProperty.all(const Size(200, 50)), )
以上三种方案都可以实现需求,优先推荐第一种仅用styleFrom的写法,代码最简洁冗余最少。
内容的提问来源于stack exchange,提问作者MN.
相关产品推荐
相关产品推荐

