我所读到的所有内容都建议您可以使用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(!mount)部分可防止出现我在重绘或类似情况之前调用处理时发生的错误,并且此输出有效,它正在正确更改布尔值的状态,实际上并没有更新颜色直到您强制窗口小部件重新绘制。
答案 0 :(得分:1)
showDialog直接不能更改该值,但是这样做您的对话框必须是有状态的小部件。
从代码中可以看出,您必须创建另一个有状态的小部件,该小部件将返回整个警报对话框,类似于下面的代码。
您必须传递新的有状态小部件中所需的所有变量。
import 'package:flutter/material.dart';
class Homestack extends StatefulWidget {
@override
_HomestackState createState() => _HomestackState();
}
class _HomestackState extends State<Homestack> {
String dropdownValue ;
@override
Widget build(BuildContext context) {
return new Container(
color: Colors.blue,
padding: const EdgeInsets.all(20),
child: GestureDetector(
child: new Text("Tap ME!"),
onTap: (){
return showDialog(
context: context,
builder: (context){
return xyz(
server3Selected: false,
greyTheme: Colors.blueAccent,
server1Selected: false,
server2Selected: false,
);
}
);
},
)
);
}
}
class xyz extends StatefulWidget {
Color greyTheme ;
bool server1Selected;
bool server2Selected;
bool server3Selected;
xyz({Key key, this.greyTheme,this.server1Selected,this.server2Selected,this.server3Selected}): super(key: key);
@override
_xyzState createState() => _xyzState();
}
class _xyzState extends State<xyz> {
@override
Widget build(BuildContext context) {
return AlertDialog(
backgroundColor: widget.greyTheme,
content: Form(
child: Column(
children: <Widget>[
ButtonTheme(
child: RaisedButton(
onPressed: (){
if (!mounted) return;
setState(() {
widget.server1Selected = true;
widget.server2Selected = false;
widget.server3Selected = false;
});
},
color: widget.server1Selected == true ? Colors.pink : Colors.blue,
child: Text(
'Server 1',
style: TextStyle(
color: Colors.red,
),
),
),
),
],
),
),
);
}
}
答案 1 :(得分:0)
从flutter文档中:如果您尝试更改按钮的颜色并且没有任何效果,请检查是否传递了非null的onPressed或onLongPress回调。