Flutter iOS 与 flutter 相互通信升级

Flutter iOS 与 flutter 相互通信升级

iOS端代码:

bash 复制代码
import Foundation
import flutter_boost


class HYFlutterCommonChannel: NSObject {
    
    @objc public static let share = HYFlutterCommonChannel()
    
    var channel: FlutterMethodChannel
    
    lazy var map: [String:(_ call: FlutterMethodCall, _ result:@escaping FlutterResult) -> Void] = {
        return [
            "notifyNativeEventResult":notifyNativeEventResult,
            "getISBuildRelease":getISBuildRelease,
        ]
    }()
    
    override init() {
        channel = FlutterMethodChannel.init(name: "Flutter/common", binaryMessenger: FlutterBoost.instance().engine().binaryMessenger)
        super.init()
        // 注册 flutter 回调原生方法
        channel.setMethodCallHandler {[weak self] (call, result) in
            let method = self?.map[call.method]
            method?(call, result)
        }
    }
    
    @objc public static func start() {
        _ = HYFlutterCommonChannel.share
    }
    
    // 获取版型状态
    func getISBuildRelease(call: FlutterMethodCall, result:@escaping FlutterResult) {
        result(false)
    }
    
    func notifyNativeEventResult(call: FlutterMethodCall, result:@escaping FlutterResult) {
        guard let arguments = call.arguments as? [String:AnyObject],
                let type = arguments["type"] as? String else {
            return
        }
        
        switch type {
        case "selectCountryAreaCode":
            do{
//                if code = {(code: String?) in
//                    if let _code = code {
//                        self.channel.invokeMethod("onCountryAreaCodeResult", arguments: _code)
//                    }
//                }
                
                if let tabBarVC = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController,
                   let naVC = tabBarVC.selectedViewController as? UINavigationController {
                    
                    let vc = HYAreaCodeController()
                    vc.complete = {(code: String?) in
                        if let _code = code {
                            self.channel.invokeMethod("onCountryAreaCodeResult", arguments: _code)
                        }
                    }
                    naVC.navigationController?.pushViewController(vc as UIViewController, animated: true)
                }
            }
            
            break
            
        default:
            break
        }
        
        
    }
}

原生 控制器代码

bash 复制代码
class HYAreaCodeController: UIViewController {
    
    
    public var complete: ((_ code: String?)->())?
    
    lazy var codeBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.red
        btn.addTarget(self, action: #selector(codeBtnClick(_:)), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.codeBtn.frame = CGRect.init(x: 100, y: 100, width: 100, height: 40)
        self.view.addSubview(self.codeBtn)
    }
    
    
    @objc func codeBtnClick(_ sender: UIButton) {
        
        if let callback = self.complete {
            callback("将选中数据返回给Flutter")
        }
    }
    
}

到此原生使用完毕

Flutter代码

bash 复制代码
import 'dart:collection';

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

class CommonChannel {
  CommonChannel() {
    init();
  }

  // ignore: constant_identifier_names
  static const MethodChannel channel_common = MethodChannel("Flutter/common");

  // ignore: non_constant_identifier_names
  static final channel_handlers = HashMap<String, MethodCallHandler>();

  void init() {
    channel_common.setMethodCallHandler((call) async {
      channel_handlers[call.method]?.call(call);
    });
  }

  void registerMethodCallHandler(String method, MethodCallHandler handler) {
    channel_handlers[method] = handler;
  }

// 获取版本状态 true -> Release
  Future<bool?> getISBuildRelease() async {
    return channel_common.invokeMethod("getISBuildRelease");
  }

  /// 打开 code 界面
  void selectAreaCode() {
    notifyNativeEventResult("selectCountryAreaCode", {});
  }

//
  void notifyNativeEventResult(String eventType, Map arguments) {
    // 第一个参数表示 method,方法名称,原生端会解析此参数
    // 第二个参数,类型任意使用Map
    // 返回 Future, 原生端返回的数据
    channel_common.invokeMethod(
        "notifyNativeEventResult", {"type": eventType, "arguments": arguments});
  }

  Future<T?> notifyNativeEventResultT<T>(String eventType, Map arguments) {
    return channel_common.invokeMethod<T?>(
        "notifyNativeEventResult", {"type": eventType, "arguments": arguments});
  }

// 注册 监听回调
// 原生会将数据返回过来,直接取 argumets即可
  void registerOnCountryAreaCodeResultHandler(MethodCallHandler? handler) {
    channel_handlers["onCountryAreaCodeResult"] = handler;
  }
}

Flutter使用

bash 复制代码
 // 使用 NavigationChannel
Channels.common.selectAreaCode();
相关推荐
茶底世界之下6 小时前
花瓣要更柔和,还是更有反差?用 Awaking 做一次对比度取舍
ios
yuanlaile20 小时前
2026年全新Flutter 跨平台开发全栈学习资料整理
flutter·getx·鸿蒙 next·flutter开发鸿蒙·flutter入门实战·flutter全栈
Anhty1 天前
2026最新免费手机音频处理工具 !!
android·功能测试·ios·智能手机·音视频
2501_915909061 天前
iOS应用从开发到上架App Store的完整发布流程与步骤指南
android·ios·小程序·https·uni-app·webview
初雪云1 天前
UniApp 云打包拿到 IPA 后,真正的发布工作才刚开始
ios·自动化·编辑器·产品经理·iphone
Lancker1 天前
没有 Mac 也能上架 iOS:GitHub Actions 全自动构建 + 签名 + TestFlight 送审实录
macos·ios·github
茶底世界之下1 天前
晚霞要多暖?用 Awaking 只改色温做一次取舍
ios
恋猫de小郭1 天前
Genkit Dart 1.0 发布,Flutter 原生的 AI Agent 终于完整了
android·前端·flutter
第10086个小白1 天前
flutter桌面端打包方式(Inno Setup Compiler)版本
前端·flutter
酒神dnspup1 天前
多地区网站可用性监控怎么做?DNSPup 从基线到告警的完整实战
运维·ios·云计算·iphone·dns·网络监控