Navigator.push() inside showdialog not working

筅森魡賤 提交于 2021-01-01 09:27:29

问题


Trying to navigate to a new screen using Navigator.push(), but it's not working. I have created a custom class to show AlertDialog and call the class with the object to show alertDialog

_customerAlertDialog.showConfirmAlertDialog(
   context: context,
   title: "Login In",
   subTitle: "You need to login to purchase.",
   onTapResponse: (bool val) async {
     if (val) {
       /// close AlertDialog
       Navigator.of(context).pop();
       Navigator.of(context).push(MaterialPageRoute(builder: (context) => LoginScreen()));
       print("show the login screen");

     } else {
       //TODO : when user click no.
     }
   });

navigator.pop() is working, print statement is working, but Navigator.push is not working. Also tried this:

Navigator.push(context,MaterialPageRoute(builder: (context) => LoginScreen())); 

回答1:


The context object that you use in Navigator.of(context).pop() isn't aware of the dialog.

If your custom alert dialog is calling showDialog, consider passing on the BuildContext object that is returned by the builder:

showDialog(
  context: context,
  builder: (BuildContext ctx) { 
    // ctx is a context object that will be aware of the dialog
    // consider passing this along to onTapResponse as an argument
  },
);

Then you can use that BuildContext to get the navigator that will be able to close the dialog:

onTapResponse: (BuildContext ctx, bool val) async {
  if (val) {
    // close AlertDialog
    Navigator.of(ctx).pop();
    Navigator.of(ctx).push(MaterialPageRoute(builder: (context) => LoginScreen()));
    print("show the login screen");
  } else {
    //TODO : when user click no.
  }
}


来源:https://stackoverflow.com/questions/63142538/navigator-push-inside-showdialog-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!