首页 > 解决方案 > 更改 Flutter 的 FlatButton onPressed 的颜色

问题描述

我想在单击按钮时更改按钮的颜色和文本。但它没有改变。我在 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)),
            )
     ),
   ),

标签: fluttercolorswidgetrefresh

解决方案


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

而且它是颤振生命周期规则,当调用 setState() 时,然后自动调用 build() 方法,它会像以前一样影响你的变量。


推荐阅读