Flutter 2中MaterialApp的buttonTheme对ElevatedButton不生效如何解决?
Flutter 2.0 之后废弃的旧按钮组件(RaisedButton/FlatButton/OutlineButton)使用的buttonTheme配置,对新增的ElevatedButton/TextButton/OutlinedButton三类组件不生效,新版按钮有独立的主题配置字段,你可以直接修改ThemeData配置如下即可实现和原有逻辑一致的全局样式:
ThemeData( // 旧的buttonTheme可以保留给还没替换的旧按钮用,也可以直接删除 buttonTheme: ButtonThemeData( textTheme: ButtonTextTheme.primary, height: 40, buttonColor: Color(0xff00a89b), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(50)) ) ), // 新增ElevatedButton全局主题配置 elevatedButtonTheme: ElevatedButtonThemeData( style: ButtonStyle( // 固定高度40 fixedSize: MaterialStateProperty.all(const Size.fromHeight(40)), // 按钮背景色 backgroundColor: MaterialStateProperty.all(const Color(0xff00a89b)), // 按钮文字颜色,对应原有ButtonTextTheme.primary的浅色文字效果 foregroundColor: MaterialStateProperty.all(Colors.white), // 圆角配置 shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(50)) ) ) ) ) )
如果你需要调整不同交互状态下的样式(比如按下、禁用状态的色值),也可以给MaterialStateProperty传入对应状态的配置:
- 示例:按下时背景色加深
backgroundColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.pressed)) { return const Color(0xff00877d); } return const Color(0xff00a89b); })
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

