我希望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());
}
不幸的是,它似乎没有效果,你能看出为什么吗?
1条答案
按热度按时间4jb9z9bj1#
您应该使用注册的
MethodChannel
通道进行呼叫你的Kotlin代码应该是这样的
我建议使用
WillPopScope
小部件来处理dart代码中的反按