I want my flutter app to get a notification every time the android system back button is pressed, and furthermore, I want to otherwise disable the back button. So this is the code I have on the kotlin side of things:
package com.example.ui
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
override fun onBackPressed() {
// send message to flutter that the system back button was pressed
val flutterEngine = getFlutterEngine()
if (flutterEngine != null) {
MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, "backButtonChannel").invokeMethod("backButtonPressed", null)
}
}
}
and here's my flutter app main function:
Future<void> backButtonPressed() async {
// Code to run when the back button is pressed
print('PRESSED!');
}
const platform = MethodChannel('com.example.ui/back_button');
void main() {
WidgetsFlutterBinding.ensureInitialized();
platform.setMethodCallHandler((call) async {
if (call.method == "backButtonPressed") {
return backButtonPressed();
}
});
return runApp(MyApp());
}
Unfortunately it seems to have no effect, are you able to see why?
You should make a call by using registered MethodChannel
channel
Your kotlin code should be like
MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, "com.example.ui/back_button").invokeMethod("backButtonPressed", null)
I suggest to use WillPopScope
widget to handle back press from dart code