关于flutter:如何在MaterialButton或RaisedButton上应用主题?

How to apply theme on MaterialButton or RaisedButton?

有人可以帮助指出我们如何为按钮定义基本主题并在每个按钮上使用它吗? 我到处都只发现textTheme而不是buttonTheme示例?

即使在buttonTheme上,我们如何定义文本颜色?
因为在按钮本身上,我们可以像color: Colors.blue一样直接进行操作


一种方法是在MaterialApp中的theme中定义buttonTheme

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void main() {
  runApp(MaterialApp(
    home: Home(),
    theme: ThemeData(
        accentColor: Colors.redAccent,
        buttonTheme: ButtonThemeData(
           buttonColor: Colors.blueAccent,
           shape: RoundedRectangleBorder(),
           textTheme: ButtonTextTheme.accent,
           ....
    )),
  ));
}

class Home extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("Button Theme"),
          backgroundColor: Colors.green),
      body: Center(
          child: RaisedButton( //Button Color is as define in theme
        onPressed: () {},
        child: Text("Send"), //Text Color as define in theme
      )),
    );
  }
}

使用此MaterialApp下定义的所有按钮,将保留此主题样式。

文本颜色将是ThemeData中的accentColor定义,就像我定义的textTheme: ButtonTextTheme.accent一样,因此它将选择accentColor

theme中定义的按钮选择主题样式


看起来您还需要向按钮提供textColor。
如何创建自定义按钮?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MyButton extends StatelessWidget {
  final String text;
  final Color textColor;
  final Color buttonColor;
  final Function() onPressed;
  MyButton({
    @required this.text,
    this.buttonColor = const Color(0xFF000000) /** Default buttonColor */,
    @required this.onPressed,
    this.textColor = const Color(0xFFDDDDDD) /** Default textColor */,
  });
  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      color: buttonColor,
      onPressed: onPressed,
      child: Text(text,
          style: TextStyle(
            color: textColor,
            fontSize: 20.0,
          )),
    );
  }
}

您也可以像上面/下面给出的答案一样定义按钮颜色。

[更新]
根据注释的请求,这就是您传递onPressed函数的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Home extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("Button Theme"),
          backgroundColor: Colors.green),
      body: Center(
        child: MyButton( //My custom button
        text:"Hit me",
        onPressed: () { print("Ouch! Easy pal!! :p") },
        textColor = const Color(SOME CUSTOM COLOUR)
      )),
    );
  }
}