Albyx97
Albyx97

Reputation: 31

How to send app in background when back button is pressed

I'm trying to avoid the default behaviour of Flutter, instead of closing app when the back button (of the smartophone of course) is pressed I will send the app in background, so when I try to reopen the app it returns on the last screen.

I also tried a solution that I have found here, but didn't work. This is the code:

 return WillPopScope(
    onWillPop: () async =>
       await SystemChannels.platform.invokeMethod('SystemNavigator.pop'),
    child: Scaffold(

It also closes the app and don't send it in background. The screen that contains the code showed above is the last route.

Upvotes: 1

Views: 1128

Answers (2)

Chirag Kalathiya
Chirag Kalathiya

Reputation: 414

Flutter plugin for sending mobile applications to the background. Supports iOS and Android.

move_to_background: ^1.0.2

WillPopScope(
  child: MaterialApp(...),
  onWillPop: () async {
    MoveToBackground.moveTaskToBack();
    return false;
  },
);

Upvotes: 0

CopsOnRoad
CopsOnRoad

Reputation: 267474

You can use MethodChannel for this, invoke a method from Flutter that will trigger a method in Java.

// in flutter use something like this
methodChannel.invokeMethod("homeButton");

And in Java, you can create a method like:

public void homeButton() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

More info on how to write platform specific code.

Upvotes: 2

Related Questions