Flutter - How to check if dialog is shown when using go_router

2.6k Views Asked by At

I was using Navigator 1 then I migrated to go_router to support deep links and web.
Sometimes when I send HTTP requests, I show a loading dialog using showDialog() until the response is processed, after processing I need to check if a dialog is shown or not, if shown I dismiss it using Navigator.of(context).pop().

When I was using Navigator 1, I used to do that in this way:
if (ModalRoute.of(context)?.isCurrent == false) Navigator.of(context).pop();
But now after migrating to go_router this doesn't work as I found that ModalRoute.of(context) always equals to null whether there is a dialog shown or not.

I tried using if (Navigator.of(context).canPop()) Navigator.of(context).pop();, but this doesn't differentiate between dialogs and screens, if there is no dialog shown it pops the current screen.

3

There are 3 best solutions below

0
On

you can create the base class for dialog and define as below. what ever dialog do you want to create extends the base class

Note: Don't forget to call supper class's methods if you are override the base class

abstract class BaseDialog {
      @protected
      final BuildContext context;
      bool _dialogShow = false;
    
      BaseDialog(this.context);
    
      Future<Object?> show() async {
        _dialogShow = true;
        return null;
      }
    
      void dismiss() {
        if (_dialogShow) {
          _dialogShow = false;
          context.pop();
        }
      }
    }
1
On

You can do this by checking the location of GoRouter

if (GoRouter.of(context).location == '/dialog'){  Check here
    context.pop();
}

Assuming your dialog route has path /dialog

3
On

I just use context.pop() on dialog dismiss.

Previously did it this way, but tends to throw.

Set a Global variable:

GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>();

In GoRouter specify:

navigatorKey: navKey

Pop dialog the 'old' way with:

Navigator.pop(navKey.currentContext!);

Correct me if it gives issues please.