Container(
margin: EdgeInsets.fromLTRB(220.w,155.h,0,0),
child: IconButton(
onPressed: (){
setState(() {
ChangeProfile(context);
});
},
icon: Icon(Icons.wifi_protected_setup),
),
),
这是打开 AlertDialog 以更改配置文件的代码。
void ChangeProfile(BuildContext context) {
final pro = Provider.of<Pro>(context, listen: false);
US(context);
int count = 0;
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return AlertDialog(
// RoundedRectangleBorder - Dialog 화면 모서리 둥글게 조절
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
//Dialog Main Title
title: Column(
children: <Widget>[
Container(
width: 50.w,
height: 50.h,
child: Image.asset(
pro.currentProfile
),
)
],
),
//
content: SizedBox(
width: 230.w,
height: 230.h,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox
(
width: 70.w,
height: 70.h,
child: OutlinedButton(
onPressed: (){
setState(() { // setState() 추가.
pro.currentProfile= 'image_profile/profile_1.png';
});
},
child: Image.asset('image_profile/profile_1.png'),
),
),
SizedBox(
width: 70.w,
height: 70.h,
child: OutlinedButton(
onPressed: (){
setState(() { // setState() 추가.
pro.currentProfile= 'image_profile/profile_2.png';
});
},
child: Image.asset('image_profile/profile_2.png'),
),
),
这样,当按下AlertDialog中的按钮时,Provider中的currentProfile变量就会改变。
actions: <Widget>[
TextButton(
child: Text(
"닫기",
style: TextStyle(
color: Colors.black,
),
),
onPressed: () {
setState(() {
Navigator.pop(context);
});
},
),
],
点击关闭按钮就会弹出
PrintImage(
imagetext: pro.currentProfile,
xsize: 100.0,
ysize: 100.0,
hhh: 90.0,
),
当 currentProfile 变量发生变化时,父窗口小部件将输出类似这样的内容
AlertDialog 内的值也已成功更改,当我使用 StatefulBuilder 检查时,它会实时更改。当我关闭 AlertDialog 时,父小部件不执行任何操作。
当按下另一个 TextButton 时,PrintImage 会响应更改后的 currentProfile 值。
有没有办法关闭AlertDialog并刷新构建?
最佳答案
是的,有办法。
从您的 changeProfile
方法返回 showDialog
(即 Future)
由于 changeProfile
方法返回 Future,我们现在可以在 changeProfile
上使用 .then 方法,并可以使用 setState
刷新构建。
一旦警报对话框关闭,future 就会完成并执行 .then 方法。
更正一处:方法名称应以小驼峰命名法开头,因此应为changeProfile,而不是ChangeProfile。
Container(
margin: EdgeInsets.fromLTRB(220.w,155.h,0,0),
child: IconButton(
onPressed: (){
changeProfile(context).then((value) {
setState(() {
// update your widget
})
}
);
},
icon: Icon(Icons.wifi_protected_setup),
),
),
Future<void> changeProfile(BuildContext context) {
final pro = Provider.of<Pro>(context, listen: false);
US(context);
int count = 0;
return showDialog<void>(
// paste rest of your code here
);
}
关于flutter - AlertDialog 关闭后 Statefulwidget 不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71286766/