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();
相关推荐
丿Wayne44 分钟前
iOS Token 刷新实战(Actor 避免并发重复刷新)
ios·swift·token·actor·swift并发
用户21816970493013 小时前
Flutter ClipPath
flutter
用户21816970493015 小时前
Flutter 折叠组件 ExpansionTile ExpansionPanelList
flutter
终端安全笔记21 小时前
iOS 27 给了租赁一个新工具,但它只认受监督的设备
android·网络·安全·ios
大熊猫侯佩21 小时前
独立 App 首发完成 iPhone Duo 展开态适配
ios·swiftui·swift
光影少年1 天前
setImmediate 和 setTimeout(0) 的区别
android·前端·react.js·ios·前端框架
2501_916008891 天前
SSE 和 gRPC 流式接口如何抓包,调试 SSE 与 gRPC 流式接口
网络协议·计算机网络·网络安全·ios·adb·https·udp
不羁的木木2 天前
给鸿蒙 App 增加用系统应用打开文件的能力 —— open_app_file 的鸿蒙使用指南
flutter·harmonyos
HouWan2 天前
Flutter: MediaQuery.of(context) 为什么可能拖慢页面?
android·flutter·ios
用户38034165882972 天前
Broadcast Extension 里的 Live Activity:一次跨进程妥协
ios·音视频开发