更改Flutter的FlatButton的颜色onPressed

时间:2019-10-23 04:14:08

标签: flutter colors widget refresh

我想在单击按钮时更改按钮的颜色和文本。但它并没有改变。我在setState中更改变量,并使用三元运算符设置文本和颜色。 希望您能帮到大家。

Container(
     padding: EdgeInsets.symmetric(horizontal: 15,vertical: 15),
     alignment: Alignment.bottomCenter,
     child: SizedBox(
            width: double.infinity, //Full width
            height: 40,
            child: FlatButton(
                child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
                onPressed: () {
                    setState(() {
                      stopSelling = !stopSelling;
                    });
                  },
                textColor: Colors.white,
                color: stopSelling?Colors.red:Colors.green,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            )
     ),
   ),

2 个答案:

答案 0 :(得分:3)

您的代码是完美的,但是我不知道您在哪里声明了stopSelling变量,但是我很确定您已经在build()方法中声明了stopSelling,因此您必须在build()方法之外声明stopSelling变量,在类内部(statefull或无状态)。

波动的生命周期规则是,在调用setState()时会自动调用build()方法,该变量将像以前一样影响您的变量。

答案 1 :(得分:0)

尝试一下。...

Container(
      padding: EdgeInsets.symmetric(horizontal: 15,vertical: 15),
      alignment: Alignment.bottomCenter,
      child: SizedBox(
          width: double.infinity, //Full width
          height: 40,
          child: stopSelling? FlatButton(
            child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
            onPressed: () {
              setState(() {
                stopSelling = !stopSelling;
              });
            },
            textColor: Colors.white,
            color:  Colors.red,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ):FlatButton(
            child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
            onPressed: () {
              setState(() {
                stopSelling = !stopSelling;
              });
            },
            textColor: Colors.white,
            color: Colors.green,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
      ),
    )