79259267

Date: 2024-12-06 20:16:08
Score: 2.5
Natty:
Report link

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 ♥

Reasons:
  • Blacklisted phrase (0.5): I need
  • RegEx Blacklisted phrase (1.5): reputation
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Muscler
  • User mentioned (0): @enrik
  • Low reputation (1):
Posted by: Horacio Duca