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

學習記錄,每天不停進步。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/37207.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/37207.shtml
英文地址,請注明出處:http://en.pswp.cn/news/37207.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Linux——基礎IO(1)

目錄 0. 文件先前理解 1. C文件接口 1.1 寫文件 1.2 讀文件 1.3 輸出信息到顯示器 1.4 總結 and stdin & stdout & stderr 2. 系統調用文件I/O 2.1 系統接口使用示例 2.2 接口介紹 2.3 open函數返回值 3. 文件描述符fd及重定向 3.1 0 & 1 & 2 3.2…

【Spring Cloud Alibaba】RocketMQ的基礎使用,如何發送消息和消費消息

在現代分布式架構的開發中&#xff0c;消息隊列扮演著至關重要的角色&#xff0c;用于解耦系統組件、保障可靠性以及實現異步通信。RocketMQ作為一款開源的分布式消息中間件&#xff0c;憑借其高性能、高可用性和良好的擴展性&#xff0c;成為了眾多企業在構建高可靠性、高吞吐…

運維面試大全

文章目錄 第一階段平常怎么處理故障,思路是什么樣的公網和私網分類以及范圍,本機地址,網絡地址,廣播地址交換機的工作原理ICMP是什么干什么用的,它有哪些命令TCP和UDP協議的區別tcp有哪些控制位,分別是什么意思你是用過哪些Linux命令Linux 系統安全優化與內核優化經常使用…

stable diffusion 單張圖片換頭roop安裝配置

1.首先安裝秋葉大佬的webui 2.然后在拓展里面搜索roop,下載roop插件,然后重啟webui 3.重啟后,在文生圖和圖生圖的界面,就可以看到roop的入口 4.這里面,需要提前安裝Visual Studio. 勾選一些必要的選項,這里可以參照b站的視頻 # 秋葉版本Stablediffusion的Roop插件的安裝 …

JavaScript reduce深入了解

reduce() 是 JavaScript 數組的一個高階函數&#xff0c;它允許你將數組中的元素按順序依次合并為一個單一的值。reduce() 可以用于數組求和、計算平均值、連接字符串等各種情況。它的工作原理是通過迭代數組的每個元素&#xff0c;然后將元素和累加器進行某種操作&#xff0c;…

使用 Python 在 NLP 中進行文本預處理

一、說明 自然語言處理 &#xff08;NLP&#xff09; 是人工智能 &#xff08;AI&#xff09; 和計算語言學的一個子領域&#xff0c;專注于使計算機能夠理解、解釋和生成人類語言。它涉及計算機和自然語言之間的交互&#xff0c;允許機器以對人類有意義和有用的方式處理、分析…

Java # JVM內存管理

一、運行時數據區域 程序計數器、Java虛擬機棧、本地方法棧、Java堆、方法區、運行時常量池、直接內存 二、HotSpot虛擬機對象 對象創建&#xff1a; 引用檢查類加載檢查分配內存空間&#xff1a;指針碰撞、空閑列表分配空間初始化對象信息設置&#xff08;對象頭內&#xff0…

?可視化繪圖技巧100篇進階篇(五)-階梯線圖(Step Chart)

目錄 前言 圖表類型特征 適用場景 圖例 繪圖工具及代碼實現 ECharts SMARTBI

安卓中常見的字節碼指令介紹

問題背景 安卓開發過程中&#xff0c;經常要通過看一些java代碼對應的字節碼&#xff0c;來了解java代碼編譯后的運行機制&#xff0c;本文將通過一個簡單的demo介紹一些基本的字節碼指令。 問題分析 比如以下代碼&#xff1a; public class test {public static void main…

Java課題筆記~ JSP編程

4.1 JSP基本語法 JSP (全稱Java Server Pages) 是由 Sun Microsystems 公司倡導和許多公司參與共同創建的一種使軟件開發者可以響應客戶端請求&#xff0c;而動態生成 HTML、XML 或其他格式文檔的Web網頁的技術標準。 JSPHTMLJava JSP的本質是Servlet 訪問JSP的時候&#x…

【設計模式】原型模式

原型模式&#xff08;Prototype Pattern&#xff09;是用于創建重復的對象&#xff0c;同時又能保證性能。這種類型的設計模式屬于創建型模式&#xff0c;它提供了一種創建對象的最佳方式之一。 這種模式是實現了一個原型接口&#xff0c;該接口用于創建當前對象的克隆。當直接…

javaScript:數組的認識與使用以及相關案例

目錄 一.前言 二.數組 1.認識 2.數組的聲明 1.let arr [1,2,3,4] 2.結合構造函數&#xff0c;創建數組 注意&#xff1a; 3.數組長度的設置和獲取 注意 4.刪除數組元素 5.清空數組 三.獲取數組元素 獲取數組元素的幾種方法 1.使用方括號 [] 訪問元素&#xff1…

Keepalived+Lvs高可用高性能負載配置

環境準備 IP配置VIPnode1192.168.134.170LVSKeepalived192.168.134.100node3192.168.134.172LVSKeepalived192.168.134.100node2192.168.134.171做web服務器使用node4192.168.134.173做web服務器使用 1、準備node1與node3環境&#xff08;安裝LVS與Keepalived&#xff09;>…

基于微服務+Java+Spring Cloud +Vue+UniApp +MySql實現的智慧工地云平臺源碼

基于微服務JavaSpring Cloud VueUniApp MySql開發的智慧工地云平臺源碼 智慧工地概念&#xff1a; 智慧工地就是互聯網建筑工地&#xff0c;是將互聯網的理念和技術引入建筑工地&#xff0c;然后以物聯網、移動互聯網技術為基礎&#xff0c;充分應用BIM、大數據、人工智能、移…

滾動條樣式更改

::-webkit-scrollbar 滾動條整體部分&#xff0c;可以設置寬度啥的 ::-webkit-scrollbar-button 滾動條兩端的按鈕 ::-webkit-scrollbar-track 外層軌道 ::-webkit-scrollbar-track-piece 內層滾動槽 ::-webkit-scrollbar-thumb 滾動的滑塊 ::-webkit-scrollbar…

Android布局【RelativeLayout】

文章目錄 介紹常見屬性根據父容器定位根據兄弟組件定位 通用屬性margin 設置組件與父容器的邊距padding 設置組件內部元素的邊距 項目結構主要代碼 介紹 RelativeLayout是一個相對布局&#xff0c;如果不指定對齊位置&#xff0c;都是默認相對于父容器的左上角的開始布局 常見…

TypeScript教程(二)基礎語法與基礎類型

一、基礎語法 TypeScript由以下幾個部分組成 1.模塊 2.函數 3.變量 4.語句和表達式 5.注釋 示例&#xff1a; Runoob.ts 文件代碼&#xff1a; const hello : string "Hello World!" console.log(hello) 以上代碼首先通過 tsc 命令編譯&#xff1a; tsc …

MQTT寶典

文章目錄 1.介紹2.發布和訂閱3.MQTT 數據包結構4.Demo5.EMQX 1.介紹 什么是MQTT協議 MQTT&#xff08;消息隊列遙測傳輸協議&#xff09;&#xff0c;是一種基于發布/訂閱&#xff08;publish/subscribe&#xff09;模式的“輕量級”通訊協議&#xff0c;該協議構建于TCP/IP協…

php、 go 語言怎么結合構建高性能高并發商城。

一、php、 go 語言怎么結合構建高性能高并發商城。 將PHP和Go語言結合起來構建高性能高并發的商城系統可以通過多種方法實現&#xff0c;以利用兩種語言的優勢。下面是一些可能的方法和策略&#xff1a; 1. **微服務架構&#xff1a;** 使用微服務架構&#xff0c;將系統拆分…

安卓快速開發

1.環境搭建 Android Studio下載網頁&#xff1a;https://developer.android.google.cn/studio/index.html 第一次新建工程需要等待很長時間&#xff0c;新建一個Empty Views Activity 項目&#xff0c;右上角選擇要運行的機器&#xff0c;運行就安裝上去了(打開USB調試)。 2…