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 ♥