flutter - 更改 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)),
)
),
),
解决方案
你的代码是完美的,但我不知道你在哪里声明你的 stopSelling 变量,但我很确定你已经在 build() 方法中声明了 stopSelling,所以你必须在 build() 方法之外和内部声明 stopSelling 变量类(有状态或无状态)。
而且它是颤振生命周期规则,当调用 setState() 时,然后自动调用 build() 方法,它会像以前一样影响你的变量。
推荐阅读
- json - 将 Json 数据从本地文件加载到 REACT 中的 Typescript 变量中
- java - 如何使用ajax将Json Array从java servlet发送到JSP?
- xamarin - Xamarin Android 应用程序不以 Xamarin 地图和自定义 pin 开头
- javascript - 如何防止在支付认证成功之前在 Stripe 中创建试用订阅?
- java - 如何将内部存储中的本地文件用作 AssetFileDescriptor?
- python - 命令行中函数的返回值不正确
- c# - 验证 Worker Service 上的配置文件
- ios - 重命名 XCode 项目后面临的问题
- c++ - 无法使用 C++ Poco 库正确克隆 JSON 数组
- airflow-scheduler - 大量任务时,气流调度程序不调度(或缓慢)