问题描述
我用 cognito in Flutter 制作了一个登录表单,我想在登录成功或失败后用 AlertDialog
通知用户。用户尝试失败后,对话框显示,它弹回当前屏幕,在我按下警报对话框 (OK
) 中的按钮后,它抛出错误 Looking up a deactivated widget's ancestor is unsafe.
我不明白为什么会发生这种情况,我是新手,所以不确定如何解决它。
这是登录方法:
void loginToCognito() async {
final storage = FlutterSecureStorage();
await storage.write(key: "e",value: email);
await storage.write(key: "p",value: password);
String message;
try {
_user = await _userService.login(email,password);
message = 'User successfully logged in!';
if (!_user.confirmed) {
message = 'Please confirm user account';
}
return showAlertDialog(
context,message,Navigator.pushNamed(context,SecondScreen.id),);
} on CognitoClientException catch (e) {
if (e.code == 'InvalidParameterException' ||
e.code == 'NotAuthorizedException' ||
e.code == 'UserNotFoundException' ||
e.code == 'ResourceNotFoundException') {
message = e.message;
/// This is where the error happpens
return showAlertDialog(
context,Navigator.pop(context),);
} else {
message = 'An unkNown client error occurred';
return showAlertDialog(
context,);
}
} catch (e) {
message = 'An unkNown error occurred';
return showAlertDialog(
context,);
}
}
这是alertDialog:
showAlertDialog(
BuildContext context,String message,void function,) {
// Create button
Widget okButton = FlatButton(
child: Text("OK"),onpressed: () {
Navigator.of(context).pop();
},);
// Create AlertDialog
AlertDialog alert = AlertDialog(
title: Text('User Login'),content: Text(message),actions: [
okButton,],);
// show the dialog
showDialog(
context: context,builder: (BuildContext context) {
return alert;
},);
}
这个错误是因为第一个 Navigator.pop(context);
发生了吗?如果是这样,解决此问题的最佳方法是什么?提前致谢。我已尝试使用 final globalScaffoldKey = GlobalKey<ScaffoldState>();
,但未能解决问题。
解决方法
你从来没有在你的 showAlertDialog() 中使用过这个函数,但我明白你在这里想要完成什么,所以让我解释一下:
不要将函数设置为等于Navigator.pop...,而是检查你FlatButton中的函数是否为null,然后调用Navigator.pop...如果不为null,则FlatButton应该调用该函数你给出了一个论点。
您也从错误的上下文中弹出,让我重命名您的变量:
showAlertDialog(
BuildContext contextFromCall,//this context is an argument you specified
String message,void function,) {
// Create button
Widget okButton = FlatButton(
child: Text("OK"),onPressed: () {
Navigator.of(contextFromCall).pop(); //here you pop that context
},);
...
}
但是,您使用不同的上下文显示 AlertDialog:
showDialog(
context: contextFromCall,builder: (BuildContext contextInsideDialog) { //you should pop this one
return alert;
},);
因此,解决方案是将 contextInsideDialog 传递给您的警报,然后将其传递给您的 okButton,您应该在其中使用该上下文调用 Navigator.pop