当前,我有一个AlertDialog
和一个IconButton
。用户可以单击IconButton,每次单击都有两种颜色。问题是我需要关闭AlertDialog并重新打开以查看颜色图标的状态更改。我想在用户单击时立即更改IconButton的颜色。
这里是代码:
bool pressphone = false;
//....
new IconButton(
icon: new Icon(Icons.phone),
color: pressphone ? Colors.grey : Colors.green,
onPressed: () => setState(() => pressphone = !pressphone),
),
这是因为您需要将AlertDialog
放在自己的StatefulWidget
中,并将所有状态操作逻辑移到该颜色上。
更新:
void main() => runApp(MaterialApp(home: Home()));
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
child: Text('Open Dialog'),
onPressed: () {
showDialog(
context: context,
builder: (_) {
return MyDialog();
});
},
)));
}
}
class MyDialog extends StatefulWidget {
@override
_MyDialogState createState() => new _MyDialogState();
}
class _MyDialogState extends State<MyDialog> {
Color _c = Colors.redAccent;
@override
Widget build(BuildContext context) {
return AlertDialog(
content: Container(
color: _c,
height: 20.0,
width: 20.0,
),
actions: <Widget>[
FlatButton(
child: Text('Switch'),
onPressed: () => setState(() {
_c == Colors.redAccent
? _c = Colors.blueAccent
: _c = Colors.redAccent;
}))
],
);
}
}
showDialog(
context: context,
builder: (context) {
String contentText = "Content of Dialog";
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text("Title of Dialog"),
content: Text(contentText),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text("Cancel"),
),
FlatButton(
onPressed: () {
setState(() {
contentText = "Changed Content of Dialog";
});
},
child: Text("Change"),
),
],
);
},
);
},
);
当前正在检索我使用的Dialog的值
showDialog().then((val){
setState (() {});
print (val);
});
示例第一个屏幕
onPressed: () {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AddDespesa();
}).then((val) {
setState(() {});
print(val);
}
);
}
第二屏幕
AlertDialog(
title: Text("Sucesso!"),
content: Text("Gasto resgristrado com sucesso"),
actions: <Widget>[
FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.pop(context, true);
},
),
],
);
将打印为真,
文档建议您在AlertDialog的StatefulBuilder
部分中使用content
。甚至StatefulBuilder docs实际上都有一个带有对话框的示例。
它的作用是为您提供新的上下文和setState函数,以便在需要时进行重建。
来自文档的示例代码:
showDialog<void>(
context: context,
builder: (BuildContext context) {
int selectedRadio = 0;
return AlertDialog(
content: StatefulBuilder( // You need this, notice the parameters below:
builder: (BuildContext context, StateSetter setState) {
return Column(
mainAxisSize: MainAxisSize.min,
children: List<Widget>.generate(4, (int index) {
return Radio<int>(
value: index,
groupValue: selectedRadio,
onChanged: (int value) {
setState(() => selectedRadio = value);
},
);
}),
);
},
),
);
},
);
正如我所提到的,这就是showDialog docs上所说的内容:
[...]生成器返回的窗口小部件未与该位置共享上下文showDialog最初是从中调用的。 使用StatefulBuilder或如果对话框需要动态更新,请自定义StatefulWidget。