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 的颜色?
基础教程推荐
- 固定小数的Android Money Input 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01
- Android文本颜色不会改变颜色 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01
- :hover 状态不会在 iOS 上结束 2022-01-01
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01
- LocationClient 与 LocationManager 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
