Flutter中ElevatedButtonTheme的textStyle无法修改ElevatedButton文字颜色
问题原因
ElevatedButton的样式规则中,ButtonStyle内的textStyle的color属性不会直接作用于按钮文本,Flutter优先使用foregroundColor属性控制按钮文本、图标等所有前景元素的颜色,你配置的textStyle颜色被按钮默认的foregroundColor覆盖,因此没有生效。- 你当前的写法不能达到修改文字颜色的预期效果,
textStyle仅用于控制字体大小、字重、字体家族等文本属性,颜色类的前景样式需要单独配置foregroundColor才会生效。
正确修改方案
方案1:全局主题配置(推荐)
直接在ElevatedButtonTheme的ButtonStyle中新增foregroundColor配置即可,示例代码如下:
elevatedButtonTheme: ElevatedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Color(0xff64ffda)), // 新增前景色配置,直接控制按钮文字颜色 foregroundColor: MaterialStateProperty.all(Colors.black), textStyle: MaterialStateProperty.all(TextStyle( // 这里可配置字体大小、字重等其他文本属性,无需指定color fontSize: 16, fontWeight: FontWeight.w500 )), ), ),
方案2:单独指定Text组件样式
如果仅需要修改单个按钮的文本颜色,也可以直接在Text组件的style中指定颜色:
child: ElevatedButton( onPressed: _submit, child: Padding( child: Text( AppLocalizations.key(context, 'save'), style: TextStyle(color: Colors.black), ), ), ),
内容的提问来源于stack exchange,提问作者rozerro
相关产品推荐
相关产品推荐

