Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter showDialog with navigator key rather than passing context

Tags:

flutter

Currently its very hectic to show dialog from any layer of code in app just because one has to pass context in it. Hence i thought to pass navigatorKey.currentContext (Navigator key is a global key passed to Material app navigatorKey parameter) to show dialog. But i got the error

"Navigator operation requested with a context that does not include a Navigator.The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget."

The issue is showDialog calls Navigator.of(context) internally and which looks for the navigator ancestor which ofcourse will return null as the navigator is itself the root. Hence it will not find the navigator as ancestor.

Is there a way we can directly pass the navigator state/context to showDialog function to show the dialog? Or is there a more easy way to show Dialog without passing context to it if we want to show it from bloc?

like image 710
Ayush P Gupta Avatar asked Mar 15 '19 18:03

Ayush P Gupta


People also ask

What is the difference between dialog and ShowDialog in flutter?

In flutter, a dialog is a widget which popup on the screen when button is pressed. When a dialog box is popup on the screen its disabled the all other functions until we close or provide the information to it. A showDialog provide the information to the users as it popup on the current screen of the application.

How do I close the navigator dialog in Visual Studio?

If the application has multiple Navigator objects, it may be necessary to call Navigator.of (context, rootNavigator: true).pop (result) to close the dialog rather than just Navigator.pop (context, result). Returns a Future that resolves to the value (if any) that was passed to Navigator.pop when the dialog was closed.

Is showshowdialog's context correct in nested navigator?

showDialog's context is not correct in nested navigator. · Issue #23808 · flutter/flutter · GitHub Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community. By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement.

How to access navigatorstate outside of build context in flutter?

Setting up get_it is covered here it's about 6 lines of code to do that quickly. In Flutter GlobalKeys can be used to access the state of a StatefulWidget and that's what we'll use to access the NavigatorState outside of the build context.


1 Answers

I found a simple solution:

navigatorKey.currentState.overlay.context

I use this in a redux middleware where I keep navigatorKey, and want to show a dialog globally anywhere in the app everytime I dispatch a specific action.

like image 53
KLD Avatar answered Nov 02 '22 19:11

KLD