MethodChannel

Flutter与原生交互的一种办法,此种办法传递的是办法,能够双向传递,能够带着参数,双向传递都能够有回来值

Flutter给原生端发送音讯
  • Flutter端代码装备
final methodChannel = const MethodChannel('test_method_channel');
Future<void> sendMessageFromMethodChannel() async {
  final result = await methodChannel.invokeMethod("method_one");
  print(result);
}

界说发送音讯 MethodChannel生成对应的channel,需要指定channelname

发送音讯运用的是:invokeMethod

指定办法名,也能够带参数,有回来值

  • 原生端代码装备

先界说一个MethodChannelManager管理类

var channel: FlutterMethodChannel
init(messager: FlutterBinaryMessenger) {
 channel = FlutterMethodChannel(name: "test_method_channel", binaryMessenger: messager)
  channel.setMethodCallHandler { (call , result) in
  print("接纳到了来自Flutter发送的办法\(call.method)")
  result("我是原生回来给Flutter的音讯")
  }
}

界说好channel,注册办法 setMethodCallHandler

AppDelegate进口函数处需要初始化

let messager = window.rootViewController as! FlutterBinaryMessenger
MethodChannelManager(messager: messager)

Flutter与原生交互方式之MethodChannel使用

运转项目后,点击触发事情,打印如下:

Flutter与原生交互方式之MethodChannel使用

原生(iOS为例)Flutter发送音讯
  • iOS原生端装备
var channel: FlutterMethodChannel
  init(messager: FlutterBinaryMessenger) {
    channel = FlutterMethodChannel(name: "test_method_channel", binaryMessenger: messager)
    channel.setMethodCallHandler { (call , result) in
      print("接纳到了来自Flutter发送的办法\(call.method)")
      result("我是原生回来给Flutter的音讯")
      self.startTimer()
    }
  }
 
  func startTimer() {
    Timer.scheduledTimer(timeInterval: TimeInterval(2), target: self, selector: #selector(sendMessageToFlutter), userInfo: nil, repeats: false)
  }
 
  @objc func sendMessageToFlutter() {
    channel.invokeMethod("ios_method", arguments: "我是原生主动发送过来的") {(result) in
      print(result)
    }
  }

原生端发送音讯也是调用 invokeMethod,也能够以闭包方式接纳到Flutter端的回来值

  • Flutter端装备
Future<void> setMethodChannelCallHandler() async {
  methodChannel.setMethodCallHandler((call) async {
    print('Flutter收到了原生端的办法:${call.method}, 传参为:${call.arguments} ---- call: $call');
    return Future.value('我是Flutter回传给原生端的数据');
  });
}
@override
void initState() {
  // TODO: implement initState
    super.initState();
    setMethodChannelCallHandler();
}

Flutter中装备的setMethodChannelCallHandler也能够给原生回传数据,直接回来一个 Future即可

运转打印结果如下:

Flutter与原生交互方式之MethodChannel使用