[英]How do I input a TextButton background color to a function in Flutter/dart
I'm trying to create a function where under buildKey I can input two elements, the background color and the soundNumber so that when buildKey is called I can enter say buildKey(red, 2) or buildKey(colName: red, soundNumber: 2) etc.我正在尝试创建一个 function,在 buildKey 下我可以输入两个元素,背景颜色和 soundNumber 以便在调用 buildKey 时我可以输入 buildKey(red, 2) 或 buildKey(colName: red, soundNumber: 2)等等
The soundNumber element works however no matter what I try I can't get a valid background color input to work. soundNumber 元素有效,但无论我尝试什么,我都无法获得有效的背景颜色输入。
Any help hugely appreciated.非常感谢任何帮助。
class _MyHomePageState extends State<MyHomePage> {
void playSound(int noteNumber) {
AssetsAudioPlayer.newPlayer().open(
Audio("/assets/note$noteNumber.wav"),
);
}
Expanded buildKey({required MaterialColor color, required int soundNumber}) {
return Expanded(
child: TextButton(
style: TextButton.styleFrom(
backgroundColor: color,
),
onPressed: () {
playSound(soundNumber);
},
child: const Text(''),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
buildKey(color: MaterialStateProperty.all(Colors.red), soundNumber: 1),
],
),
),
);
}
}
You have to use MaterialStateProperty
class to apply color.您必须使用
MaterialStateProperty
class 来应用颜色。 Here is the Example:这是示例:
TextButton(
child: Text('Your Text'),
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
onPressed: () {},
),
Was helped with a fix.得到了修复的帮助。 It kept the original styleFrom on the TextButton instead of using MaterialStateProperty.
它保留了 TextButton 上的原始 styleFrom,而不是使用 MaterialStateProperty。 I was inputing the argument incorrectly so using Color as the data type worked.
我输入的参数不正确,因此使用 Color 作为数据类型有效。
Expanded buildKey({required Color colName, required int soundNumber}) {
return Expanded(
child: TextButton(
style: TextButton.styleFrom(
backgroundColor: colName,
),
onPressed: () {
playSound(soundNumber);
},
child: const Text(''),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
buildKey(colName: Colors.red, soundNumber: 1),
buildKey(colName: Colors.orange, soundNumber: 2),
buildKey(colName: Colors.yellow, soundNumber: 3),
buildKey(colName: Colors.green, soundNumber: 4),
buildKey(colName: Colors.teal, soundNumber: 5),
buildKey(colName: Colors.blue, soundNumber: 6),
buildKey(colName: Colors.purple, soundNumber: 7),
],
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.