dart - 在颤动中改变按钮的状态
问题描述
我想要在颤动中做的是当我按下button1时它启用button2然后它禁用自己并且我想对button2做同样的事情。
bool button1 = true;
bool button2 = false;
void _button1(){
setState(){
button1=false;button2=true;
}
}
void _button2(){
setState(){
button1=true;button2=false;
}
}
new MaterialButton(onPressed: button1 ? _button1 :null,child: Text("button1"),color: Colors.greenAccent,),
new MaterialButton(onPressed: button2 ? _button2 :null,child: Text("button2"),color: Colors.greenAccent,),
但这对我不起作用,因为当我按下 button1 时没有任何反应。
解决方案
This Works with Single bool Variable :
class Page1State extends State<Page1> {
bool buttonState = true;
void _buttonChange() {
setState(() {
buttonState = !buttonState;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Button State'),
),
body: Center(
child: Wrap(
children: <Widget>[
MaterialButton(
onPressed: buttonState ? _buttonChange : null,
child: Text("button1"),
color: Colors.greenAccent,
),
MaterialButton(
onPressed: buttonState ? null : _buttonChange,
child: Text("button2"),
color: Colors.greenAccent,
),
],
)));
}
}
Also In your Code SetState is not Correct:
it Should Be:
bool button1 = true;
bool button2 = false;
void _button1() {
setState(() {
button1 = false;
button2 = true;
});
}
void _button2() {
setState(() {
button1 = true;
button2 = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Button State"),
),
body: Center(
child: Wrap(
children: <Widget>[
MaterialButton(
onPressed: button1 ? _button1 : null,
child: Text("button1"),
color: Colors.greenAccent,
),
MaterialButton(
onPressed: button2 ? _button2 : null,
child: Text("button2"),
color: Colors.greenAccent,
)
],
),
),
);
}
}
推荐阅读
- ios - 禁用/启用 3D Touch 上的图标。迅速
- javascript - 可排序的 select2 交换值
- python - 删除字典列表中的重复值时出现问题?
- flask - 如何连接到远程 SQL Server 以在烧瓶中进行登录验证
- python - 如何在 Python 中使用 post 请求在 elasticsearch 中建立索引?
- php - 向 LoggableListener 添加额外选项
- css - 修复 react-select 下拉列表的高度(React Material UI)
- django - 为什么在 API 中使用 URL 参数而不是请求正文?
- hybris - Hybris Beanshell脚本启动业务流程
- dialogflow-es - 我们如何在 DialogFlow Web 演示 iframe 中传递一些参数