How to make Flutter module return to native Android activity after the native Android activity launches a secondary route?

802

Solution 1

Here is extract from the documentation:

If the route name starts with a slash, then it is treated as a "deep link", and before this route is pushed, the routes leading to this one are pushed also. Even if the route was just /a, the app would start with / and /a loaded. https://api.flutter.dev/flutter/material/MaterialApp/initialRoute.html

You could try re-naming your '/settings' route to 'settings'.

Solution 2

Try SystemNavigator.pop() to pop the topmost flutter route

More details at https://api.flutter.dev/flutter/services/SystemNavigator/pop.html

Share:
802
Pedro Massango
Author by

Pedro Massango

Associate Android Developer | Kotlin | Dart | Android Studio | Flutter | Youtuber | Content Writer

Updated on November 28, 2022

Comments

  • Pedro Massango
    Pedro Massango over 1 year

    I'm adding flutter to a existing Android project and everything is working fine, except one thing:

    My Android project has only one Flutter module. In that Flutter module I have two routes that will be shown in different parts of the Android project:

      initialRoute: '/',
      routes: {
        '/': (_) => MyHomePage(),
        '/settings': (_) => _SettingsPage()
      }
    

    In the Android Activity if I start a new Flutter activity with this:

    startActivity(
                FlutterActivity
                    .withCachedEngine(flutterEngineId)
                    .build(this)
            )
    

    It will start Flutter with the default page route (/) which is the expected result. Then in this Flutter page if I navigate back, it will pop the Flutter engine and navigate back to the Android Activity. Everything good for now.

    But if I start a Flutter activity with a custom initial route, and then I press the back button, it will not pop the Flutter engine and navigate to the Android activity but to the initial Flutter route (in this case the / route).

        startActivity(
            FlutterActivity
                .withNewEngine()
                .initialRoute("/settings")
                .build(this)
        )
    

    Why we're having this behavior if we are specifying the initial route while starting the FlutterActivity?

    And if this is the expect behavior, then what is the best way of make it navigate to the Android activity?