Flutter - How do I toggle the color of a RaisedButton upon click?(Flutter - 如何在点击时切换 RaisedButton 的颜色?)
问题描述
我正在尝试切换凸起按钮的颜色.最初按钮应该是蓝色的,当它被按下时它会变成灰色.现在我有一个名为 pressAttention 的布尔值,它被设置为 false.我正在使用它来最初将其设置为 false.当按下按钮时,它会切换 pressAttention bool,但似乎小部件永远不会再次更新.
I am trying to toggle the color of a raised button. Initially the button should be blue and when it is pressed it turns to grey. Right now I have a bool value called pressAttention and it is set to false. I am using this to initially set this the false. When the button is pressed it toggles the pressAttention bool, but it seems that the widget is never updated again.
new RaisedButton(
child: new Text("Attention"),
textColor: Colors.white,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
color: pressAttention?Colors.grey:Colors.blue,
onPressed: () => doSomething("Attention"),
)
void doSomething(String buttonName){
if(buttonName == "Attention"){
if(pressAttention = false){
pressAttention = true;
} else {
pressAttention = false;
}
}
}
推荐答案
这个按钮需要在 StatefulWidget 的 ,并且State必须有一个成员变量State 的 build 中创建bool pressAttention = false;.正如 Edman 建议的那样,您需要在 setState 回调中进行状态更改,以便 Widget 重绘.
This button will need to be created in the build of a State of a StatefulWidget, and the State must have a member variable bool pressAttention = false;. As Edman suggests, you need to make state changes in a setState callback for the Widget to redraw.
new RaisedButton(
child: new Text('Attention'),
textColor: Colors.white,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
color: pressAttention ? Colors.grey : Colors.blue,
onPressed: () => setState(() => pressAttention = !pressAttention),
);
这篇关于Flutter - 如何在点击时切换 RaisedButton 的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Flutter - 如何在点击时切换 RaisedButton 的颜色?
基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
