Punk420g
Punk420g

Reputation: 131

Sending your application to background when back button is pressed in flutter

Flutter code to send the app to background when back button is pressed. I want to minimize the app to background when i click the back button like home button does to apps and now when i click the back button it kills the app. I am using willPopScope to get it work but no help

Upvotes: 12

Views: 13247

Answers (5)

Horacio Duca
Horacio Duca

Reputation: 11

12.2024 UPDATE

Following @Muscler and @enrik answer, Platform code (Kotlin) changed once again and I just made adjustments:

In your MainActivity.kt file add the following code:

import android.os.Bundle
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
private val CHANNEL = "android_app_retain"

override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)

    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
        if (call.method == "sendToBackground") {
            moveTaskToBack(true) 
            result.success(null)
        } else {
            result.notImplemented()
        }
    }
}

 override fun onBackPressed() {
    moveTaskToBack(true)
 }
}

then in your Dart code invoke method adding following:

const platform = MethodChannel('android_app_retain');

Future<void> _sendToBackground() async {
  try {
    await platform.invokeMethod('sendToBackground');
  } on PlatformException catch (e) {
    print("Error while sending app to background: $e");
  }
}

@override
Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: () async {
    await _sendToBackground(); // Sends app to background when pressing "back"
    return false; // Prevents app from closing
  },
  child: Scaffold(
    ...
  ),
 );
}

Please thumbs up if works! I need to reach 2 reputation lol ♥

Upvotes: 1

SuperCode
SuperCode

Reputation: 632

I found this package on pub.dev and it worked well for me and it's easy to use

https://pub.dev/packages/move_to_background

EDIT: This package is no longer maintained therefore please consider other answers except this one.

Upvotes: 13

enrik
enrik

Reputation: 51

07.2023 UPDATE

Following @Muscler answer:

Platform code (Kotlin) changed again:

    import androidx.annotation.NonNull
    import io.flutter.embedding.android.FlutterActivity
    import io.flutter.embedding.engine.FlutterEngine
    import io.flutter.plugin.common.MethodChannel

    class MainActivity: FlutterActivity() {
        override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
            super.configureFlutterEngine(flutterEngine)

            MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "android_app_retain").apply {
                setMethodCallHandler { method, result ->
                    if (method.method == "sendToBackground") {
                        moveTaskToBack(true)
                    }
                }
            }
        }
   }

If it changes again, you should look at flutter docs: https://docs.flutter.dev/platform-integration/platform-channels?tab=android-channel-kotlin-tab

The dart code still the same, so it's:

var _androidAppRetain = MethodChannel("android_app_retain");

@override
Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: () {
    if (Platform.isAndroid) {
      if (Navigator.of(context).canPop()) {
        return Future.value(true);
      } else {
        _androidAppRetain.invokeMethod("sendToBackground");
        return Future.value(false);
      }
    } else {
      return Future.value(true);
    }
  },
  child: Scaffold(
    ...
  ),
);
}

Upvotes: 5

Muscler
Muscler

Reputation: 149

03.2020 UPDATE

As @user1717750 wrote - The dart code remains the same, so it's:

var _androidAppRetain = MethodChannel("android_app_retain");

@override
Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: () {
    if (Platform.isAndroid) {
      if (Navigator.of(context).canPop()) {
        return Future.value(true);
      } else {
        _androidAppRetain.invokeMethod("sendToBackground");
        return Future.value(false);
      }
    } else {
      return Future.value(true);
    }
  },
  child: Scaffold(
    ...
  ),
);
}

The code in the MainActivity() should look like this:

class MainActivity: FlutterActivity() {

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);

    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "android_app_retain").apply {
        setMethodCallHandler { method, result ->
            if (method.method == "sendToBackground") {
                moveTaskToBack(true)
            }
        }
    }
}
}

Upvotes: 8

grandleaf
grandleaf

Reputation: 1192

From here: https://medium.com/stuart-engineering/%EF%B8%8F-the-tricky-task-of-keeping-flutter-running-on-android-2d51bbc60882

PLAT FORM CODE:

class MainActivity : FlutterActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GeneratedPluginRegistrant.registerWith(this)

        MethodChannel(flutterView, "android_app_retain").apply {
            setMethodCallHandler { method, result ->
                if (method.method == "sendToBackground") {
                    moveTaskToBack(true)
                }
            }
        }
    }
}

YOUR DART CODE:

Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        if (Platform.isAndroid) {
          if (Navigator.of(context).canPop()) {
            return Future.value(true);
          } else {
            _androidAppRetain.invokeMethod("sendToBackground");
            return Future.value(false);
          }
        } else {
          return Future.value(true);
        }
      },
      child: Scaffold(
        drawer: MainDrawer(),
        body: Stack(
          children: <Widget>[
            GoogleMap(),
          ],
        ),
      ),
    );
  }

CREDIT TO: Sergi Castellsagué Millán

Upvotes: 2

Related Questions