How to apply theme on MaterialButton or RaisedButton?
有人可以帮助指出我们如何为按钮定义基本主题并在每个按钮上使用它吗? 我到处都只发现
即使在
因为在按钮本身上,我们可以像
一种方法是在
例如:
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 )), ); } } |
使用此
文本颜色将是
看起来您还需要向按钮提供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, )), ); } } |
您也可以像上面/下面给出的答案一样定义按钮颜色。
[更新]
根据注释的请求,这就是您传递
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) )), ); } } |