作者:踏山321 | 来源:互联网 | 2022-11-27 20:14
有人可以帮助指出我们如何为按钮定义基本主题并在每个按钮上使用它吗?我到处都只发现textTheme
但找不到buttonTheme
示例?
甚至buttonTheme
我们如何定义文本颜色?因为在按钮本身上,我们可以直接像color: Colors.blue
1> anmol.majhai..:
做到这一点的方法之一是定义buttonTheme
在theme
中MaterialApp
:
例如:
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
主题样式。
文字颜色将是我accentColor
定义的中的ThemeData
定义,textTheme: ButtonTextTheme.accent
因此它将选择accentColor
按中定义的按钮选择主题样式 theme
2> Dennis..:
看起来您还需要向按钮提供textColor。如何创建自定义按钮?
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
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)
)),
);
}
}