Flutter插件开发之MethodChannel交互基础

MethodChannel是Flutter和原生交互的基础,通过传入Flutter插件的名字,调用invokeMethod方法,便可以调用原生的方法,有点类似于Java的反射。

static const MethodChannel _channel

= const MethodChannel('scene_camera_plugin');

static Future get platformVersion async {

  //调用原生的代码

  final String? version = await _channel.invokeMethod('getPlatformVersion');

  return version;

}


在Android端,通过一个处理类,继承自MethodCallHandler需要接受Flutter调用方法的请求,返回原生数据。

public class SceneCameraPlugin implements FlutterPlugin, MethodCallHandler {

  // The MethodChannel that will the communication between Flutter and native Android

  // This local reference serves to register the plugin with the Flutter Engine and unregister it

  // when the Flutter Engine is detached from the Activity

  private MethodChannel channel;

  @Override

  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {

    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "scene_camera_plugin");

    channel.setMethodCallHandler(this);

  }

  @Override

  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {

  //如果Flutter端调用了getPlatformVersion方法,那么就返回数据;

  //返回数据通过MethodCall的success方法

    if (call.method.equals("getPlatformVersion")) {

      result.success("Android " + android.os.Build.VERSION.RELEASE);

    } else {

      result.notImplemented();

    }

  }

  @Override

  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {

    channel.setMethodCallHandler(null);

  }


两个平台一样,都会获取MethodCall对象 和FlutterResult对象。

MethodCall对象保存了方法名和参数,通过方法名确定调用具体的方法,通过参数获取具体的数据。

FlutterResult对象可以将数据返回给Flutter.

你可能感兴趣的:(Flutter插件开发之MethodChannel交互基础)