目前,我有一个带IconButton
的AlertDialog
。用户可以点击IconButton,我每次点击都有两种颜色。问题是,我需要关闭AlertDialog并重新打开,才能看到颜色图标的状态变化。我想在用户单击IconButton时立即更改它的颜色。
代码如下:
bool pressphone = false;
//....
new IconButton(
icon: new Icon(Icons.phone),
color: pressphone ? Colors.grey : Colors.green,
onPressed: () => setState(() => pressphone = !pressphone),
),
发布于 2019-07-28 20:33:07
使用StatefulBuilder来使用setState inside对话框,并仅更新其中的小部件。
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>[
TextButton(
onPressed: () => Navigator.pop(context),
child: Text("Cancel"),
),
TextButton(
onPressed: () {
setState(() {
contentText = "Changed Content of Dialog";
});
},
child: Text("Change"),
),
],
);
},
);
},
);
发布于 2018-08-22 18:22:21
这是因为您需要将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;
}))
],
);
}
}
发布于 2019-10-20 21:15:41
在StatefulBuilder
的content
部分使用AlertDialog。即使是StatefulBuilder docs实际上也有一个带有对话框的示例。
它所做的是为您提供一个新的上下文,以及在需要时重新构建的setState函数。
示例代码:
showDialog(
context: context,
builder: (BuildContext context) {
int selectedRadio = 0; // Declare your variable outside the builder
return AlertDialog(
content: StatefulBuilder( // You need this, notice the parameters below:
builder: (BuildContext context, StateSetter setState) {
return Column( // Then, the content of your dialog.
mainAxisSize: MainAxisSize.min,
children: List<Widget>.generate(4, (int index) {
return Radio<int>(
value: index,
groupValue: selectedRadio,
onChanged: (int value) {
// Whenever you need, call setState on your variable
setState(() => selectedRadio = value);
},
);
}),
);
},
),
);
},
);
正如我提到的,这就是showDialog docs上所说的
...构建器返回的小部件不与最初调用showDialog的位置共享上下文。如果对话框需要动态更新StatefulBuilder或自定义StatefulWidget,请使用。
https://stackoverflow.com/questions/51962272
复制相似问题