Flutter与原生数据交互MethodChannel

Flutter端

channel定义

声明channel,并且定义name为myApp。

const channel = const MethodChannel('myApp');

注册方法,等待原生调用

/*注册方法,供原生调用*/
void register() {
  channel.setMethodCallHandler((call) async {
    /// 逻辑处理...
    print('收到原生调用flutter:'+call.method+'参数:'+call.arguments);
    if (call.method == 'work') {
      return call.arguments;
    }
  });
}

flutter调用原生

/*flutter调用原生*/
void invokeMethod(String method, Function(dynamic result) callBack, [dynamic arguments]) async {
  dynamic result = await channel.invokeMethod(method, arguments);
  if (callBack != null) {
    callBack(result);
  }
}

flutter端使用

引入文件

import 'package:flutter_app/channel.dart' as channel;

注册channel

void main() {
  runApp(MyApp());
  channel.register();
}

flutter调用原生

/*flutter调用原生*/
channel.invokeMethod('work', (result){
  print('收到原生返回'+result);
},'123');

原生端(iOS)

Flutter原生交互类定义

class FlutterNativePlugin: NSObject {
    static let plugin = FlutterNativePlugin()
    private let channelName = "myApp"
    private var channel: FlutterMethodChannel?
    
    func register(messenger: FlutterBinaryMessenger?, callBack: (() -> Void)? = nil) {
        guard let _messenger = messenger else { return }
        FlutterNativePlugin.plugin.registerMethod(messenger: _messenger, callBack: callBack)
    }
    
    /// 注册方法,等待flutter调用
    private func registerMethod(messenger: FlutterBinaryMessenger, callBack: (() -> Void)? = nil) {
        channel = FlutterMethodChannel(name: channelName, binaryMessenger: messenger)
        guard let _channel = channel else { return }
        _channel.setMethodCallHandler { (call, result) in
            /// 逻辑处理...
            if (call.method == "work") {
                print("收到flutter调用原生:" + call.method + "参数:" + (call.arguments as? String ?? ""))
                result(call.arguments)
                guard let _callBack = callBack else { return }
                _callBack()
            }
        }
    }
    
    // 原生调用flutter
    public func invokeMethod(method: String, gaguments: Any?, callBack: ((_ result: Any?) -> Void)?) {
        guard let _channel = channel else { return }
        _channel.invokeMethod(method, arguments: gaguments) { (result) in
            guard let _callBack = callBack else { return }
            _callBack(result)
        }
    }
}

注册及使用

在Appdelegate中注册

/// 注册
FlutterNativePlugin.plugin.register(messenger: (self.window.rootViewController as? FlutterViewController)?.binaryMessenger)
/// 原生调用flutter
DispatchQueue.main.asyncAfter(deadline: .now()+1) {
    FlutterNativePlugin.plugin.invokeMethod(method: "work", gaguments: "123456") { (result) in
        print("swift收到flutter回调"+(result as? String ?? ""))
    }
}

执行结果

Runner[98650:6658789] flutter: 收到原生调用flutter:work参数:123456
swift收到flutter回调123456
收到flutter调用原生:work参数:123
Runner[98650:6658789] flutter: 收到原生返回123

注意点

  1. flutter和原生,都必须先注册channel,然后才能使用。
  2. 注册为异步执行,需有一定的时延才能使用调用方法。

你可能感兴趣的:(Flutter与原生数据交互MethodChannel)