我所读到的所有内容都表明您可以使用 SetState 完成这项工作。这是我一直在使用的,它不会重绘。
class ServerSelectionState extends State<ServerSelection> {
bool server1Selected, server2Selected, server3Selected = false;
@override
void initState() {
setState(() {
server1Selected= false;
server2Selected= false;
server3Selected= false;
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
//Basically have an onTap method from a ListTile that opens a dialog, like this:
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: greyTheme,
content: Form(
child: Container(
children: <Widget>[
ButtonTheme(
child: RaisedButton(
onPressed: (){
if (!mounted) return;
setState(() {
server1Selected = true;
server2Selected = false;
server3Selected = false;
});
},
color: server1Selected == true ? Colors.pink : Colors.blue,
child: Text(
'Server 1',
style: TextStyle(
color: Colors.red,
),
),
),
),
],
),
),
),
}
);
}
这将在热重载时很好地更新按钮颜色,但在此之前,重绘似乎并不快乐。if (!mounted) 部分防止了我看到的关于在重绘或类似之前调用 dispose 的错误,并且打印输出这正在工作,它正在正确更改布尔值的状态,它实际上并没有更新颜色直到您强制小部件重绘。