【问题标题】:change color of the Flutter's FlatButton onPressed更改 Flutter 的 FlatButton onPressed 的颜色
【发布时间】:2020-02-19 06:14:57
【问题描述】:

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

【问题讨论】:

  • 你在哪里初始化你的 stopSelling 变量?

标签: flutter colors widget refresh


【解决方案1】:

试试这个....

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)),
          ),
      ),
    )

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢。那是我的错误。
    猜你喜欢
    • 2018-06-13
    • 2020-12-01
    • 2020-06-29
    • 2012-11-30
    • 1970-01-01
    • 2019-08-19
    • 2020-05-27
    • 2019-06-23
    • 2018-10-24
    相关资源
    最近更新 更多