当前位置: 首页 > news >正文

flutter开发实战-MethodChannel实现flutter与iOS双向通信

flutter开发实战-MethodChannel实现flutter与iOS双向通信

最近开发中需要iOS与flutter实现通信,这里使用的MethodChannel

如果需要flutter与Android实现双向通信,请看
https://blog.csdn.net/gloryFlow/article/details/132218837

这部分与https://blog.csdn.net/gloryFlow/article/details/132218837中的一致,这里实现一下iOS端的MethodChannel设置。

一、MethodChannel

MethodChannel:用于传递方法调用(method invocation)。
通道的客户端和宿主端通过传递给通道构造函数的通道名称进行连接

一个应用中所使用的所有通道名称必须是唯一的
使用唯一的域前缀为通道名称添加前缀,比如:samples.flutter.dev/battery

官网 https://flutter.cn/docs/development/platform-integration/platform-channels

二、在flutter端实现MethodChannel

我们需要创建一个名字为"samples.flutter.dev/test"的通道名称。
通过invokeNativeMethod与setMethodCallHandler来实现

invokeNativeMethod:调用Android端的代码
setMethodCallHandler:设置方法回调,用于接收Android端的参数

代码如下

import 'package:flutter/services.dart';//MethodChannel
const methodChannel = const MethodChannel('samples.flutter.dev/test');class FlutterMethodChannel {/** MethodChannel* 在方法通道上调用方法invokeMethod* methodName 方法名称* params 发送给原生的参数* return数据 原生发给Flutter的参数*/static Future<Map> invokeNativeMethod(String methodName,[Map? params]) async {var res;try {if (params == null) {res = await methodChannel.invokeMethod('$methodName');} else {res = await methodChannel.invokeMethod('$methodName', params);}} catch (e) {res = {'Failed': e.toString()};}return res;}/** MethodChannel* 接收methodHandler* methodName 方法名称* params 发送给原生的参数* return数据 原生发给Flutter的参数*/static void methodHandlerListener(Future<dynamic> Function(MethodCall call)? handler) {methodChannel.setMethodCallHandler(handler);}
}

使用该MethodChannel,我们需要使用MethodChannel
使用代码如下

  void initState() {// TODO: implement initStatesuper.initState();setMethodHandle();}void setMethodHandle() {FlutterMethodChannel.methodHandlerListener((call) {print("methodHandlerListener call:${call.toString()}");if ("methodToFlutter" == call.method) {print("methodToFlutter arg:${call.arguments}");}return Future.value("message from flutter");});}Future<void> invokeNativeMethod() async {var result = await FlutterMethodChannel.invokeNativeMethod("methodTest", {"param":"params from flutter"});print("invokeNativeMethod result:${result.toString()}");}void testButtonTouched() {invokeNativeMethod();}void dispose() {// TODO: implement disposesuper.dispose();}

这里我们处理了方法methodToFlutter来接收iOS端的传参数调用,同时处理后我们将结果"message from flutter"返回给iOS端。
我们调用iOS端的方法methodTest,并且传参,获取iOS端传回的结果。

三、在iOS端实现MethodChannel

在iOS中,同样我们实现了MethodChannel。
iOS实现MethodChannel需要实现FlutterPlugin,实现registerWithRegistrar
我这里命名一个SDFlutterMethodChannelPlugin继承NSObject,通过实现registerWithRegistrar方法

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:kFlutterMethodChannelName binaryMessenger:[registrar messenger] codec:[FlutterStandardMethodCodec sharedInstance]];SDFlutterMethodChannelPlugin *instance = [[SDFlutterMethodChannelPlugin alloc] initWithMethodChannel:methodChannel];// 将插件注册为来自Dart端的传入方法调用的接收者 在指定的“ FlutterMethodChannel”上。[registrar addMethodCallDelegate:instance channel:methodChannel];
}

同样在插件SDFlutterMethodChannelPlugin中设置setMethodCallHandler及调用Flutter的方法

例如

__weak typeof(self) weakSelf = self;[self.methodChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {[weakSelf handleMethodCall:call result:result];}];

通过handleMethodCall可以处理方法methodTest处理接收来自flutter的参数,处理后并将结果返回给flutter。

整体代码如下

SDFlutterMethodChannelPlugin.h

#import <Foundation/Foundation.h>
#import <Flutter/Flutter.h>@class SDFlutterMethodChannelPlugin;typedef void (^SDFlutterMethodChannelPluginCompletionBlock)(SDFlutterMethodChannelPlugin *plugin);@interface SDFlutterMethodChannelPlugin : NSObject<FlutterPlugin>- (instancetype)initWithMethodChannel:(FlutterMethodChannel *)methodChannel;@end

SDFlutterMethodChannelPlugin.m

#define kFlutterMethodChannelName @"samples.flutter.dev/test"@interface SDFlutterMethodChannelPlugin ()<FlutterStreamHandler>@property (nonatomic, strong) FlutterMethodChannel *methodChannel;@property (nonatomic, strong) NSTimer *sendMessageTimer;@end@implementation SDFlutterMethodChannelPlugin- (instancetype)initWithMethodChannel:(FlutterMethodChannel *)methodChannel {self = [super init];if (self) {self.flutterBridgeConfig = [[DFFlutterBridgeConfig alloc] init];self.methodChannel = methodChannel;__weak typeof(self) weakSelf = self;[self.methodChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {[weakSelf handleMethodCall:call result:result];}];[self startSendMessageTimer];}return self;
}+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:kFlutterMethodChannelName binaryMessenger:[registrar messenger] codec:[FlutterStandardMethodCodec sharedInstance]];SDFlutterMethodChannelPlugin *instance = [[SDFlutterMethodChannelPlugin alloc] initWithMethodChannel:methodChannel];// 将插件注册为来自Dart端的传入方法调用的接收者 在指定的“ FlutterMethodChannel”上。[registrar addMethodCallDelegate:instance channel:methodChannel];
}#pragma mark - FlutterPlugin协议方法
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {NSLog(@"config handleMethodChannel callmethod:%@,params:%@,result:%@", call.method, call.arguments, result);// 没有处理,需要单独处理NSString *method=call.method;if ([method isEqualToString:@"methodTest"]) {NSLog(@"flutter 调用到了 ios test");NSMutableDictionary *dic = [NSMutableDictionary dictionary];[dic setObject:@"result.success 返回给flutter的数据" forKey:@"message"];[dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];result(dic);} else if ([method isEqualToString:@"test2"]) {NSLog(@"flutter 调用到了 ios test2");result(@YES);} else {result(FlutterMethodNotImplemented);}
}#pragma mark - 开启定时器
- (void)sendMessageTimerAction {// 开启[self.methodChannel invokeMethod:@"methodToFlutter" arguments:@"Params from Android"];
}/**开启定时器
*/
- (void)startSendMessageTimer {if (_sendMessageTimer) {return;}//开始其实就是开始定时器_sendMessageTimer = [NSTimer timerWithTimeInterval:6 target:self selector:@selector(sendMessageTimerAction) userInfo:nil repeats:YES];//加到runloop[[NSRunLoop currentRunLoop] addTimer:_sendMessageTimer forMode:NSRunLoopCommonModes];
}/**结束定时器*/
- (void)stopSendMessageTimer {//暂停其实就是销毁计时器[_sendMessageTimer invalidate];_sendMessageTimer = nil;
}@end

在iOS中需要在AppDelegate中设置,在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中实现

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[SDFlutterMethodChannelPlugin registerWithRegistrar:[(id)[SDWeakProxy proxyWithTarget:self] registrarForPlugin:@"SDFlutterMethodChannelPlugin"]];return YES;
}

我们在iOS代码中实现MethodChanel,通过定时器NSTimer定时调用方法methodToFlutter将参数传递给Flutter端。通过在iOS端setMethodCallHandler根据方法methodTest处理接收来自flutter的参数,处理后并将结果返回给flutter。

四、小结

flutter开发实战-MethodChannel实现flutter与iOS双向通信。实现MethodChannel在flutter端与iOS端实现相互通信功能。

https://blog.csdn.net/gloryFlow/article/details/132240415

学习记录,每天不停进步。

相关文章:

flutter开发实战-MethodChannel实现flutter与iOS双向通信

flutter开发实战-MethodChannel实现flutter与iOS双向通信 最近开发中需要iOS与flutter实现通信&#xff0c;这里使用的MethodChannel 如果需要flutter与Android实现双向通信&#xff0c;请看 https://blog.csdn.net/gloryFlow/article/details/132218837 这部分与https://bl…...

华为、阿里巴巴、字节跳动 100+ Python 面试问题总结(七)

系列文章目录 个人简介&#xff1a;机电专业在读研究生&#xff0c;CSDN内容合伙人&#xff0c;博主个人首页 Python面试专栏&#xff1a;《Python面试》此专栏面向准备面试的2024届毕业生。欢迎阅读&#xff0c;一起进步&#xff01;&#x1f31f;&#x1f31f;&#x1f31f; …...

K8S系列一:概念入门

写在前面 本文组织方式&#xff1a; K8S的架构、作用和目的。需要首先对K8S整体有所了解。 K8S是什么&#xff1f; 为什么是K8S&#xff1f; K8S怎么做&#xff1f; K8S的重要概念&#xff0c;即K8S的API对象。要学习和使用K8S必须知道和掌握的几个对象。 Pod 实例 Volume 数…...

QT- QLineEdite设置自动补全功能,并修改自动补全的样式

#include <QApplication> #include <QLineEdit> #include <QCompleter> #include <QStringListModel> #include <QMainWindow>int main(int argc, char *argv[]) {QApplication app(argc, argv);// 创建一个字符串列表模型QStringListModel mode…...

解决Adobe Flash Player已被屏蔽

问题&#xff1a;该插件不支持 原因&#xff1a;现在浏览器默认禁用flash 博主当前使用的是谷歌浏览器Chrome 2个主要方法都已经失效 搜索一圈后&#xff0c;之前博客给出的2个主要方法都已经失效。 1、flash.cn 下载本地播放器 2、在chrome中打开flash的禁用开关 2023年解…...

【Spring专题】Spring之Bean的生命周期源码解析——阶段二(IOC之实例化)

目录 前言阅读准备阅读指引阅读建议 课程内容一、SpringIOC之实例化1.1 简单回顾1.2 概念回顾1.3 核心方法讲解 二、方法讲解2.1 AbstractBeanFactory#getMergedLocalBeanDefinition&#xff1a;合并BeanDefinition2.2 AbstractAutowireCapableBeanFactory#createBean&#xff…...

YOLOv8目标检测算法

YOLOv8目标检测算法相较于前几代YOLO系列算法具有如下的几点优势&#xff1a; 更友好的安装/运行方式速度更快、准确率更高新的backbone&#xff0c;将YOLOv5中的C3更换为C2FYOLO系列第一次尝试使用anchor-free新的损失函数 YOLOv8简介 YOLOv8 是 Ultralytics 公司继 YOLOv5…...

uniapp条件编译

uniapp条件编译 uni-app 将已经将可以跨平台兼容处理的组件及 API 等进行了封装&#xff0c;但是部分平台的特性无法跨平台。 由此&#xff0c;uni-app 提供了条件编译的方案&#xff0c;来处理不同平台的特定或差异。 写法 #ifdef&#xff1a; 仅在某平台存在#ifndef&#xf…...

2023年国赛数学建模思路 - 复盘:光照强度计算的优化模型

文章目录 0 赛题思路1 问题要求2 假设约定3 符号约定4 建立模型5 模型求解6 实现代码 建模资料 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 问题要求 现在已知一个教室长为15米&#xff0c;宽为12米&…...

volte端到端问题分析(一)

1、MME专载保持功能验证 **描述&#xff1a;**当无线环境较差时&#xff0c;有可能由于“Radio_Connection_with_UE_Lost” 原因造成的VoLTE通话掉话&#xff0c;如果UE发生RRC重建成功&#xff0c;手机将不会掉话。 对MME1202进行功能验证&#xff1a;开启后&#xff0c;MME专…...

微信小程序(原生)搜索功能实现

一、效果图 二、代码 wxml <van-searchvalue"{{ keyword }}"shape"round"background"#000"placeholder"请输入关键词"use-action-slotbind:change"onChange"bind:search"onSearch"bind:clear"onClear&q…...

Android AOSP源码编译——AOSP整编(二)

切换到源码目录下执行下面命令 1、初始化环境 . build/envsetup.sh //清除缓存 make clobber2、选择编译目标 lunchAOSP 预制了很多 Product。这里为了简单我们先不用真机&#xff0c;而是选择模拟器的方式&#xff0c;对于 x86_64 模拟器&#xff0c;我们选择的是 aosp_x86…...

铁是地球科学争论的核心

一项新的研究调查了地球内部铁的形态。这些发现对理解内核的结构产生了影响。 一项新的研究探索了地球内核的铁结构&#xff0c;如图中的黄色和白色所示。 资料来源&#xff1a;地球物理研究快报 地球内核以铁为主&#xff0c;铁可以多种晶体形式作为固体材料存在。&#xff08…...

TX Text Control .NET Server for ASP.NET Crack

TX Text Control .NET Server for ASP.NET Crack TX Text Control.NET Server for ASP.NET是用于Web应用程序或服务的服务器端组件。它是一个完全可编程的ASP.NET文字处理引擎&#xff0c;提供了广泛的文字处理功能。使用TX Text Control.NET Server&#xff0c;程序员可以开发…...

工作纪实36-ES跨集群迁移

1.es数据备份、恢复 https://blog.csdn.net/andy_only/article/details/111319175 2.reindex命令 https://codeleading.com/article/40964498185/ 添加配置、重启ES cd bin sh elasticsearch -d3.开源工具 https://github.com/elasticsearch-dump/elasticsearch-dump 4.…...

【MFC】11.MFC文档和单文档架构-笔记

MFC文档 之前我们在写字符雨的时候&#xff0c;将数据都存储到了视图类中&#xff0c;这是不合理的&#xff0c;视图类只负责显示&#xff0c;不应该存储任何数据 文档&#xff1a;专门存储数据用的 CDocument 文档与视图的关系&#xff1a; 创建一个文档类 单文档四个类都…...

2023年“研究生科研素养提升”系列公益讲座在线测评题目与参考答案

一、单选题 1、关于参考文献的选择&#xff0c;说法错误的是 &#xff08; &#xff09; 参考文献的选择有原创性、必要性的原则 不能过度引用 不能故意隐藏引用来源 可以引用无关参考文献 您的答案&#xff1a;D 参考答案&#xff1a;D 答案解析&#xff1a;不可以引用无关参考…...

MySQL8.xx一主两从复制安装与配置

搭建环境: 查看系统版本cat /etc/redhat-release [rootwww tools]# cat /etc/redhat-release CentOS Linux release 7.9.2009 (Core) 查看内核版本cat /proc/version 目标: 一主两从 主机IP 主机名称 端口 搭建环境 安装目录192.168.1.100 docker…...

深度学习优化器

1、什么是优化器 优化器用来寻找模型的最优解。 2、常见优化器 2.1. 批量梯度下降法BGD(Batch Gradient Descent) 2.1.1、BGD表示 BGD 采用整个训练集的数据来计算 cost function 对参数的梯度&#xff1a; 假设要学习训练的模型参数为W&#xff0c;代价函数为J(W)&#xff0c;…...

由浅入深C系列五:使用libcurl进行基于http get/post模式的C语言交互应用开发

使用libcurl进行基于http get/post模式的C语言交互应用开发 简介环境准备在线资源示例代码测试调用运行结果 简介 大多数在linux下的开发者&#xff0c;都会用到curl这个命令行工具。对于进行restful api的测试等&#xff0c;非常方便。其实&#xff0c;这个工具还提供了一个C…...

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…...

挑战杯推荐项目

“人工智能”创意赛 - 智能艺术创作助手&#xff1a;借助大模型技术&#xff0c;开发能根据用户输入的主题、风格等要求&#xff0c;生成绘画、音乐、文学作品等多种形式艺术创作灵感或初稿的应用&#xff0c;帮助艺术家和创意爱好者激发创意、提高创作效率。 ​ - 个性化梦境…...

(二)TensorRT-LLM | 模型导出(v0.20.0rc3)

0. 概述 上一节 对安装和使用有个基本介绍。根据这个 issue 的描述&#xff0c;后续 TensorRT-LLM 团队可能更专注于更新和维护 pytorch backend。但 tensorrt backend 作为先前一直开发的工作&#xff0c;其中包含了大量可以学习的地方。本文主要看看它导出模型的部分&#x…...

Robots.txt 文件

什么是robots.txt&#xff1f; robots.txt 是一个位于网站根目录下的文本文件&#xff08;如&#xff1a;https://example.com/robots.txt&#xff09;&#xff0c;它用于指导网络爬虫&#xff08;如搜索引擎的蜘蛛程序&#xff09;如何抓取该网站的内容。这个文件遵循 Robots…...

css3笔记 (1) 自用

outline: none 用于移除元素获得焦点时默认的轮廓线 broder:0 用于移除边框 font-size&#xff1a;0 用于设置字体不显示 list-style: none 消除<li> 标签默认样式 margin: xx auto 版心居中 width:100% 通栏 vertical-align 作用于行内元素 / 表格单元格&#xff…...

图表类系列各种样式PPT模版分享

图标图表系列PPT模版&#xff0c;柱状图PPT模版&#xff0c;线状图PPT模版&#xff0c;折线图PPT模版&#xff0c;饼状图PPT模版&#xff0c;雷达图PPT模版&#xff0c;树状图PPT模版 图表类系列各种样式PPT模版分享&#xff1a;图表系列PPT模板https://pan.quark.cn/s/20d40aa…...

MySQL JOIN 表过多的优化思路

当 MySQL 查询涉及大量表 JOIN 时&#xff0c;性能会显著下降。以下是优化思路和简易实现方法&#xff1a; 一、核心优化思路 减少 JOIN 数量 数据冗余&#xff1a;添加必要的冗余字段&#xff08;如订单表直接存储用户名&#xff09;合并表&#xff1a;将频繁关联的小表合并成…...

苹果AI眼镜:从“工具”到“社交姿态”的范式革命——重新定义AI交互入口的未来机会

在2025年的AI硬件浪潮中,苹果AI眼镜(Apple Glasses)正在引发一场关于“人机交互形态”的深度思考。它并非简单地替代AirPods或Apple Watch,而是开辟了一个全新的、日常可接受的AI入口。其核心价值不在于功能的堆叠,而在于如何通过形态设计打破社交壁垒,成为用户“全天佩戴…...

android RelativeLayout布局

<?xml version"1.0" encoding"utf-8"?> <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"match_parent"android:layout_height"match_parent"android:gravity&…...

华为OD机试-最短木板长度-二分法(A卷,100分)

此题是一个最大化最小值的典型例题&#xff0c; 因为搜索范围是有界的&#xff0c;上界最大木板长度补充的全部木料长度&#xff0c;下界最小木板长度&#xff1b; 即left0,right10^6; 我们可以设置一个候选值x(mid)&#xff0c;将木板的长度全部都补充到x&#xff0c;如果成功…...