颤振更改主题中所有凸起的按钮文本颜色

时间:2019-06-09 19:57:28

标签: flutter

我希望我的所有RaisedButton小部件都具有不同的textColor,如何在MaterialApp ThemeData中仅更改此内容?

2 个答案:

答案 0 :(得分:0)

如果您查看MaterialButton,将会发现它使用了ButtonThemeData中的方法getTextColor(),并且此方法考虑了枚举ButtonTextTheme来定义文字颜色。枚举项是normalaccentprimary。您可以仅基于这些颜色为RaisedButton设置全局文本颜色。

要实现该目标:

ThemeData theme = Theme.of(context);

return MaterialApp(
  ...
  theme: theme.copyWith(
    buttonTheme: theme.buttonTheme.copyWith(
      textTheme: ButtonTextTheme.accent,
    ),
  ),
);

如果您要设置与normalaccentprimary不匹配的自定义颜色,则最好的选择是使用此颜色创建自定义Widget颜色,因此您无需分别在每个RaisedButton中进行设置。

签出:

class ButtonWithCustomTextColor extends RaisedButton {
  ButtonWithCustomTextColor({
    Key key,
    @required VoidCallback onPressed,
    ValueChanged<bool> onHighlightChanged,
    ButtonTextTheme textTheme,
    // Place your custom color here
    Color textColor = Colors.blue,
    Color disabledTextColor,
    Color color,
    Color disabledColor,
    Color highlightColor,
    Color splashColor,
    Brightness colorBrightness,
    double elevation,
    double highlightElevation,
    double disabledElevation,
    EdgeInsetsGeometry padding,
    ShapeBorder shape,
    Clip clipBehavior = Clip.none,
    MaterialTapTargetSize materialTapTargetSize,
    Duration animationDuration,
    Widget child,
  }) : super(
    key: key,
    onPressed: onPressed,
    onHighlightChanged: onHighlightChanged,
    textTheme: textTheme,
    textColor: textColor,
    disabledTextColor: disabledTextColor,
    color: color,
    disabledColor: disabledColor,
    highlightColor: highlightColor,
    splashColor: splashColor,
    colorBrightness: colorBrightness,
    elevation: elevation,
    highlightElevation: highlightElevation,
    disabledElevation: disabledElevation,
    padding: padding,
    shape: shape,
    clipBehavior: clipBehavior,
    materialTapTargetSize: materialTapTargetSize,
    animationDuration: animationDuration,
    child: child,
  );
}

答案 1 :(得分:0)

对于拥有浅色应用程序但想要按钮上带有白色文本的任何人,您可以在应用程序的入口点(即声明buttonTheme的位置)调整MaterialApp。像这样:

return MaterialApp(
  theme: ThemeData.light().copyWith(
    buttonTheme: ThemeData.dark().buttonTheme
  ),
);