Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finish FlutterActivity from Flutter when integrating Flutter to native host app [Add2App]

When integrating Flutter to a host app (docs) there is a few ways to do it, one of them (simplest) is open Flutter in a new Activity via FlutterActivity class. Like this:

// Java
hostActivity.startActivity(                
  FlutterActivity.withCachedEngine("my_engine_id").build(context)
);

Traditionally for Android style windows on Flutter side we create AppBar with Back button.

This AppBar back button and Android system back button must behave the same: foreground activity must been closed (finish) when pressing to back button.

Currently system back button really closes the FlutterActivity, but how to emulate this behaviour from flutters AppBar back button?

// Dart - Flutter side
...
child: AppBar(
  leading: IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
          // WHAT MUST BE HERE?
      }),
...

PS Platform channel between Flutter side and host established - I can call any code from any side

like image 561
nail Avatar asked Jan 24 '20 14:01

nail


People also ask

Can I use Flutter inside of my existing native app?

Flutter can be embedded into your existing Android application piecemeal, as a source code Gradle subproject or as AARs. The integration flow can be done using the Android Studio IDE with the Flutter plugin or manually.

How do I navigate from Flutter page to native Android?

In Flutter, you should invoke a method through Platform Channel to call a function to navigate from the activity/view controller which hosts your Flutter, you can't directly navigate to a native view from Flutter.


2 Answers

Solution found:

SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop');

Removes the topmost Flutter instance, presenting what was before it.

On Android, removes this activity from the stack and returns to the previous activity.

Documentation here: api reference

like image 173
nail Avatar answered Sep 22 '22 11:09

nail


...
leading: BackButton(
          onPressed: () => {
            if (Navigator.canPop(context))
              {Navigator.pop(context)}
            else
              {SystemNavigator.pop()}
          },
        )
...
like image 36
NickUnuchek Avatar answered Sep 25 '22 11:09

NickUnuchek