Search code examples
flutternavigationdependenciesflutter-dependenciesflutter-desktop

Flutter: Navigation in a pop-up dialog


Is it possible to use a separate Navigator in a pop up window? Separate BuildContext?

I have a working app (APP1) and I would like to show it in a new one (APP2) (e.g. on a button press to open the existing app). APP1 has multiple pages.

I was able add the APP1 as an dependency to APP2 and load the main page in a popup dialog (Alert dialog).

The issue happens when I try to navigate through the APP1. If I click on the button in the APP1 it changes the page in the whole new app.

I would like to have separate navigation in the pop up dialog, so that the included app Navigator works only in the pop-up dialog.

What would be a preferred/possible way to achieve this?

Here is a small example: Soure code

The example consists of 2 apps (APP1 and APP2). APP2 includes APP1 and shows it in a pop up dialog.


Solution

  • You can add a nested Navigator (if you're using Navigator 1.0 in Flutter) by adding the Navigator widget inside your dialog component, that way you manage the navigation of pages within that dialog itself, create nested routes and navigate only within that navigation stack.

    You can do something like:

    class NestedDialog extends StatelessWidget {
     
       @override
       Widget build(BuildContext context) {
         return Scaffold(
           body: Navigator(
              key: <ADD_UNIQUE_KEY>, // add a unique key to refer to this navigator programmatically
              initialRoute: '/',
              onGenerateRoute: (RouteSettings settings) {
                  // here you return your own page widgets wrapped
                  // inside a PageRouteBuilder
              }
           )
         );
       }
    }
    

    Then you can even use Flutter's own showDialog and load your custom dialog widget like so:

    showDialog(context: context,
          barrierDismissible: true,
          builder: (BuildContext cxt) {
          return AlertDialog(
            content: NestedDialog()
          );
        });
    

    Something along those lines. Give that a shot. Here's a Github Gist you can run on DartPad.dev so you can see what I mean. You don't have to create two apps; just distribute your app into two main widgets, and the child pages go under each main widget's child pages; See gist https://gist.github.com/romanejaquez/d769e6e766fbacb2f5c166dd3bceab51. Run it on DartPad.dev.