我试图在用户尝试注销时显示一个对话框,并且如果用户在屏幕上显示对话框时尝试按后退按钮,我想覆盖后退按钮。为此,我尝试使用 WillPopScope 但在某个地方我做错了。它向我抛出一个错误:
注销代码:
class LogOut extends StatelessWidget {
const LogOut({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async{
print("pressed back button");
return false;
},
child: _showLoaderDialog(context),
);
}
_showLoaderDialog(BuildContext context){
AlertDialog alert=AlertDialog(
content: new Row(
children: [
CircularProgressIndicator(),
Container(margin: EdgeInsets.only(left: 7),child:Text("Logging out..." )),
],),
);
showDialog(barrierDismissible: false,
context:context,
builder:(BuildContext context){
return alert;
},
);
}
}
为什么会出现这个错误?我想问的另一个问题是,我在哪里可以编写注销逻辑代码,完成后弹出对话框并路由到登录页面屏幕?
我不确定是否明白你到底想要什么,但是如果你想在屏幕上的对话框时取消后退按钮效果,你也可以将它包装在 WillPopScope 中,如下所示:
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
Future<bool> exitConfirm() async {
return await showDialog(
barrierDismissible : false,
context: context,
builder: (context) => WillPopScope(
onWillPop: () async => false,
child: AlertDialog(
content: Row(
children: [
CircularProgressIndicator(),
Container(margin: EdgeInsets.only(left: 7),child:Text("Logging out..." )),
],),
),
),
)??false;
}
return WillPopScope(
onWillPop:exitConfirm,
child: Scaffold (
appBar: AppBar(),
body: const Center(
child: Text('Test page'),
)
),
);
}
}
结果:
请注意,我已将此行添加到 showDialog 中,因此当您单击屏幕时,对话框不会关闭:
barrierDismissible : false,
代码:
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
Future<bool> exitConfirm() async {
return await showDialog(
context: context,
builder: (context) => AlertDialog(
content: const Text('Do you want to exit ?'),
actions:[
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child:const Text('Yes'),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(false),
child:const Text('No'),
),
],
),
)??false;
}
return WillPopScope(
onWillPop:exitConfirm,
child: Scaffold (
appBar: AppBar(),
body: const Center(
child: Text('Test page'),
)
),
);
}
}
结果:
如果您只想取消后退按钮效果,您可以这样做:
onWillPop: () async => false,