flutter从Kotlin主机获取系统活动通知

osh3o9ms  于 2023-02-16  发布在  Kotlin
关注(0)|答案(1)|浏览(121)

我希望flutter应用程序在每次按下安卓系统的后退按钮时都能收到通知,而且,我还想禁用后退按钮,这是我在Kotlin方面的代码:

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)
        }
    }
}

这是我的flutter应用的主函数:

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());
}

不幸的是,它似乎没有效果,你能看出为什么吗?

4jb9z9bj

4jb9z9bj1#

您应该使用注册的MethodChannel通道进行呼叫
你的Kotlin代码应该是这样的

MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, "com.example.ui/back_button").invokeMethod("backButtonPressed", null)

我建议使用WillPopScope小部件来处理dart代码中的反按

相关问题