Search code examples
flutterflutter-navigation

Open flutter screen from Native Method call


In flutter app I have impalement one native screen using platform channel. After that I want to back in flutter and open new flutter screen but I can't open the screen.

I follow below step: 1)From flutter I call Native screen by method Channel. 2)After that from native I call flutter by method channel, but in this process I get the data from native but another screen is not open.

I have implement like this:

  Future<dynamic> searchCallHandler(MethodCall call) async {
    switch (call.method) {
      case 'openSearch':
        print('call callMe : arguments = ${call.arguments}');
     
        navigatorKey.currentState.push(
          MaterialPageRoute(builder: (context) => SearchLocation()),
        );
        return Future.value('called from platform!');
      default:
        print('Unknowm method ${call.method}');
        throw MissingPluginException();
        break;
    }
  }

in above code get the arguments value but not go in the SearchLocation Screen of the flutter.


Solution

  • You need to understand how flutter works with native here and the activity stack.

    In a flutter app, there is one main activity which extends the FlutterActivity. All your views and screens are drawn in this activity. So when you open your app there is just one activity (FlutterActivity) in the native android activity stack.

    Now when you invoke a method to start a new Activity on the native, it spins a new Activity and the android native activity stack has 2 activities.

    After that when you are calling:

    navigatorKey.currentState.push(
      MaterialPageRoute(builder: (context) => SearchLocation()),
    );
    

    through the method channel, flutter is still navigating to the the new screen in its own activity (FlutterActivity) which is behind the current visible native activity.

    So the solution is:

    Call finish() before invoking the openSearch method from the native end.

    This will destroy the current native activity and let the FlutterActivity come to foreground, and you can see the search screen in flutter.