0

我正在尝试创建一个函数,在 buildKey 下我可以输入两个元素,即背景颜色和 soundNumber,以便在调用 buildKey 时我可以输入 buildKey(red, 2) 或 buildKey(colName: red, soundNumber: 2)等等

soundNumber 元素有效,但是无论我尝试什么,我都无法获得有效的背景颜色输入。

非常感谢任何帮助。



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),
          ],
        ),
      ),
    );
  }
}
4

2 回答 2

1

你必须使用MaterialStateProperty类来应用颜色。这是示例:

TextButton(
    child: Text('Your Text'),
    style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
    onPressed: () {},
),
于 2021-10-05T17:46:04.367 回答
0

帮助修复。它保留了 TextButton 上的原始 styleFrom,而不是使用 MaterialStateProperty。我输入的参数不正确,因此使用 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),
          ],
        ),
      ),
    );
  }
}
于 2021-10-06T10:16:27.393 回答