簡體   English   中英

如何在 Flutter/dart 中將 TextButton 背景顏色輸入到 function

[英]How do I input a TextButton background color to a function in Flutter/dart

我正在嘗試創建一個 function,在 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),
          ],
        ),
      ),
    );
  }
}

您必須使用MaterialStateProperty class 來應用顏色。 這是示例:

TextButton(
    child: Text('Your Text'),
    style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
    onPressed: () {},
),

得到了修復的幫助。 它保留了 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),
          ],
        ),
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM