Flutter: How to call methods in Dart portion of the app, from the native platform using MethodChannel?

落花浮王杯 提交于 2019-11-27 02:05:01

The signature is void setMethodCallHandler(Future<dynamic> handler(MethodCall call)), so we need to provide a function at the Dart end that returns Future<dynamic>, for example _channel.setMethodCallHandler(myUtilsHandler);

Then implement the handler. This one handles two methods foo and bar returning respectively String and double.

  Future<dynamic> myUtilsHandler(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'foo':
        return 'some string';
      case 'bar':
        return 123.0;
      default:
        // todo - throw not implemented
    }
  }

At the Java end the return value is passed to the success method of the Result callback.

channel.invokeMethod("foo", arguments, new Result() {
  @Override
  public void success(Object o) {
    // this will be called with o = "some string"
  }

  @Override
  public void error(String s, String s1, Object o) {}

  @Override
  public void notImplemented() {}
});

In Swift, the return value is an Any? passed to the result closure. (Not implemented is signaled by the any parameter being the const NSObject value FlutterMethodNotImplemented.)

channel.invokeMethod("foo", arguments: args, result: {(r:Any?) -> () in
  // this will be called with r = "some string" (or FlutterMethodNotImplemented)
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!