如何修改 TextButton 被点击后的背景颜色和字体颜色

点击按钮 TextButton ,修改背景颜色和字体颜色,大概需求如下,应该一眼就能看懂。这里分享两种方法实现这需求。

可以用昨天分享的文章 Flutter TextButton 和 OutlinedButton 属性设置和参数样式 ,使用 foregroundColorbackgroundColor 分别设置字体颜色和背景颜色。但不能直接用 MaterialStateProperty.state 来判断,需要维护一个变量。再考虑到这里三个按钮,最好抽离成一个 Widget。

class CustomSelectedButton extends StatelessWidget {
  ///按钮文本
  String textContent;
  ///点击事件
  VoidCallback? onPressed;
  ///按钮状态
  bool hasFocus;

  CustomSelectedButton({this.textContent = "", this.onPressed, this.hasFocus = false});

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: onPressed,
      child:
      Text(textContent, style: TextStyle(fontSize: 13.sp)),
      style: ButtonStyle(
        foregroundColor:
        MaterialStateProperty.resolveWith(
              (states) {
            if (hasFocus) {
              //获取焦点时的颜色
              return Colors.blue;
            }
            //默认不使用背景颜色
            return Colors.white;
          },
        ),
        //按钮背景颜色
        backgroundColor: MaterialStateProperty.resolveWith((states) {
          //设置按下时的背景颜色
          if (hasFocus) {
            return ColorStyle.color_20232D;
          }
          //默认不使用背景颜色
          return null;
        }),
      ),
    );
  }
}

再去页面使用上面按钮,我这里有三个按钮,需要定义三个变量当成按钮的被点击状态。我使用 GetX 做状态和路由管理,这边按钮被点击的代码如下。如果你不是,使用 setState更新界面,但逻辑是一样的,首先将被点击按钮设置成 true,其他都设置成 false

  bool b1 = true;
  bool b2 = false;
  bool b3 = false;
  
  CustomSelectedButton(
  textContent: “xx”,
  hasFocus: b1,
  onPressed: () {
    b1 = true;
    b2 = false;
    b3 = false;
    controller.update();
  },
),

第二方法也不错,参考 How to change the text button color on press in flutter?,我这直接贴代码。

int index = -1

Color enableColor = //your color
Color disableColor = //your color

onPressed: () {
  //onPressed for button 1
  setState((){
    index = 0;
  });
},

onPressed: () {
 //onPressed for button 2
 setState((){
    index = 1;
  });
},

onPressed: () {
 //onPressed for button 3
 setState((){
    index = 2;
  });
},

color: index == 0 ? enableColor : disableColor //this is for 1 button color

color: index == 1 ? enableColor : disableColor //this is for 2 button color

color: index == 2 ? enableColor : disableColor //this is for 3 button color

这个方法很巧妙也很死板,关键是三元运算符 ? 。但如果有多个颜色或状态要改变,那就很繁琐了。

本文由老郭种树原创,转载请注明:https://guozh.net/how-to-change-the-text-button-color-on-press-in-flutter/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注