首页 > 解决方案 > 平台特定代码错误:MissingPluginException

问题描述

我想在 Flutter 中发送通知,所以我设置了特定于平台的代码(仅限 Android),但我收到以下错误:

Unhandled Exception: MissingPluginException(No implementation found for method send_notification on channel reminderChannel)

我已经清理了项目,但仍然无法正常工作。

调用方法的未来:

const platform = const MethodChannel("reminderChannel");

Future<void> invokeMethod() async {
  try {
    //FIXME Missing plugin
    int testValue = await platform.invokeMethod("send_notification");
  } on PlatformException catch (e) {}
}

invokeMethod();

主要活动:


private static final String notificationChannel = "reminderChannel";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    new MethodChannel(getFlutterView(), notificationChannel).setMethodCallHandler(
            new MethodCallHandler() {
                @Override
                public void onMethodCall(MethodCall methodCall, Result result) {
                    if (methodCall.method.equals("send_notification")) {
                        System.out.print("Android Method called");
                        result.success(5);
                    } else {
                        result.notImplemented();
                    }
                }
            }
    );
}

我希望 invokeMethod 中的 testValue 变量等于 5。

感谢您的帮助。

标签: flutterdart

解决方案


我怀疑您的频道在方法结束时被解除分配。

因此,请在您的活动中保留对 MethodChannel 的引用:

private static final String notificationChannel = "reminderChannel";
private MethodChannel mainChannel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    reminderChannel = new MethodChannel(getFlutterView(), notificationChannel)
    reminderChannel.setMethodCallHandler(
            new MethodCallHandler() {
                @Override
                public void onMethodCall(MethodCall methodCall, Result result) {
                    if (methodCall.method.equals("send_notification")) {
                        System.out.print("Android Method called");
                        result.success(5);
                    } else {
                        result.notImplemented();
                    }
                }
            }
    );
}

推荐阅读