9

iOS Flutter MethodChannel 双向通信

 1 year ago
source link: https://easeapi.com/blog/168-flutter-method-channel.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

iOS Flutter MethodChannel 双向通信

原创 2023-02-12

MethodChannel 是 Flutter提供的最常用的和 Native App 双向通信的方式。本文将演示这种通信方式的使用。

参考文档 Architectural overview: platform channels。以 Flutter 默认创建的脚手架工程为例说明。

Flutter 端的调用

首先,构建MethodChannel,可以理解为数据信道,信道通过名称唯一定位,通信时需确保 Flutter 端和 Native 端的MethodChannelname 是一致的,信道名称采用反域名的形式,比如:com.easeapi.flutter

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

修改脚手架工程main.dart文件的_MyHomePageState类:

static const channel = MethodChannel('com.easeapi.MethodChannel');

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    
    //监听来自native的事件,并向native返回结果。
    channel.setMethodCallHandler((call) {
      print(call.method);
      print(call.arguments);
      return Future.value("hello native");
    });
  }

  void _incrementCounter() async {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
    
    //请求native方法,并获取结果
    String result =  await channel.invokeMethod('send_to_ios', {"name": "easeapi"});
    print('get native result' + $result');
  }

iOS Native 端的调用

AppDelegate类中:

let channel = FlutterMethodChannel(name: "com.easeapi.MethodChannel", binaryMessenger: controller.binaryMessenger)
 
//监听来自flutter的调用
channel.setMethodCallHandler { (call: FlutterMethodCall, result:@escaping FlutterResult) in
    if (call.method == "send_to_ios") {
        result("hello flutter");
    }
    
    //从iOS层调用flutter方法
    channel.invokeMethod("send_to_flutter", arguments: ["key": "value"], result: { (_result) in
        print(_result as? String)
    })
}

其中,FlutterMethodChannel binaryMessenger参数需要传入FlutterViewControllerbinaryMessenger

完成修改,运行ios/Runner.xcworkspac。点击按钮可以看到终端中打印通信日志。

关于 FlutterViewController

FlutterViewController 在 Flutter 中是个很重要的存在,它是Flutter的容器,或者说是Flutter的画板。实际上FlutterViewController就是一个UIViewController,和原生App不同的是,Flutter中的所有内容都在于这个ViewController内做渲染,包括Flutter内的页面导航跳转。

wechat.png

您的电子邮箱地址不会被公开,必填项已用*标注。

留言内容 *

显示名称 *

电子邮箱地址 *

个人网站地址

在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次留言时使用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK