我想做的是在按下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时,什么也没发生。
最佳答案
这适用于单个 bool(boolean) 变量:
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,
),
],
)));
}
}
另外在您的代码中SetState不正确:
它应该是:
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,
)
],
),
),
);
}
}
关于dart - 在 flutter 中更改按钮的状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52342515/