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

2

9

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

Tippett answered 24/1, 2020 at 14:47 Comment(0)
T
5

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

Tippett answered 29/1, 2020 at 9:22 Comment(1)
Another option that came to mind, but I have not tried to implement it: Extend your activity from FlutterActivity and implement some kind of receiving signal to finish yourself. Via platform channels call method to send signal to finish, and your runned activity will finish yourself.Tippett
O
2
...
leading: BackButton(
          onPressed: () => {
            if (Navigator.canPop(context))
              {Navigator.pop(context)}
            else
              {SystemNavigator.pop()}
          },
        )
...
Obolus answered 26/4, 2021 at 14:58 Comment(1)
Clean and easy method.Toleration

© 2022 - 2024 — McMap. All rights reserved.