Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

flutter to get notifications from system activity from kotlin host

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading