因为模态框等于是重新打开了另一个路由,所以你在AlertDialog这个widget中间更新状态不会实时更改状态
普通模态框
showDialog(
// barrierDismissible: false, //点击外层不会关闭窗口
context: context,
builder: (context) => AlertDialog(
title: Text('Caution'),
content: Text('11111111'),
actions: [
new FlatButton(
child: new Text("Yes"),
onPressed: () {},
),
],
));
如果只是单纯的一些提示或者确认操作,这样就可以满足了,但是有时候需要在模态框上实时更新状态,比如switch或者输入框密码回显之类的,就需要这样在AlertDialog外层包一层StatefulBuilder 写法
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return StatefulBuilder(
builder: (context, state) {//state重新定义一个setState
return AlertDialog(
content: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
height: val['encrypt'] == "wpa2" ? 320 : 250,
child: Flex(
direction: Axis.vertical,
children: [
Container(
padding: EdgeInsets.symmetric(vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Remember'),
Container(
child: Switch(
value: savedWifi,
onChanged: (bool value) {
state(() { //////////setState改成state或者其他你上面定义的
savedWifi = !savedWifi;
});
},
))
],
),
),
],
)),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0)),
actions: [
FlatButton(
child: new Text("Cancel"),
onPressed: () {
state(() {
password.clear();
username.clear();
_isObscure = false;
});
Navigator.of(context).pop();
},
),
FlatButton(
child: new Text("Apply"),
onPressed: () {
Navigator.of(context).pop();
_joinWifi(val, 'join');
password.clear();
username.clear();
},
),
],
);
},
);
},
);