簡體   English   中英

如何更改 flutter 中文本按鈕的背景顏色?

[英]How can I change the background color of a textbutton in flutter?

我正在嘗試將我的FlatButton遷移到TextButton 因為自從我升級了 flutter 版本后, FlatButtons已被棄用。 我目前正在努力調整背景顏色。

舊按鈕:

FlatButton(
        height: height,
        onPressed: onPressed,
        shape: baseButtonBorder,
        color: Colors.red,
        child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
      )`

新按鈕:

TextButton(
        onPressed: onPressed,
        style: ButtonStyle(backgroundColor: Colors.red), // <-- Does not work
        child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
      ),

平面按鈕沒有color屬性,所以我嘗試使用style屬性並添加一個ButtonStyle dart 說:

The argument type 'MaterialColor' can't be assigned to the parameter type 'MaterialStateProperty<Color>'.

如何像以前對 FlatButton 所做的那樣使用紅色設置TextButtonFlatButton 我需要用紅色創建MaterialStateProperty<Color>嗎?

backgroundColor屬性是MaterialStateProperty<Color?>類型。 您可以查看Flutter 文檔

所以你必須使用MaterialStateProperty class 來應用顏色。 一個簡單的例子:

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

對於尋找更清晰、更簡單的方法的人,您可以使用TextButton.styleFrom() 例子:

TextButton(
  child: Text('Example'),
  onPressed: () {},
  style: TextButton.styleFrom(backgroundColor: Colors.red),
)

您可以在 styleFrom 中自定義幾乎任何您想要的東西。 這也適用於其他按鈕,例如ElevatedButtonOutlinedButton

試試這個方法

TextButton(
  onPressed: () {},
  child: Container(
    padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
    color: Colors.red,
    child: Text(""),
  ),
)

Textbutton添加背景顏色的最簡單方法

TextButton(
    style: TextButton.styleFrom(backgroundColor: Colors.red),
),

暫無
暫無

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

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