用pigeon kotlin swift写一个自己的插件

文章目录

          1. 创建一个flutter plugin项目
          1. 引入依赖
          1. 创建pigeons文件夹和message.dart
          1. 执行生成各个平台文件的命令
          1. base_plugin.dart
          1. BasePlugin.kt
          1. BasePlugin.swift
          1. 遇到的问题
          1. [源码](https://github.com/githubityu/base_plugin)
1. 创建一个flutter plugin项目
2. 引入依赖

pigeon: ^18.0.0

3. 创建pigeons文件夹和message.dart
dart 复制代码
import 'package:pigeon/pigeon.dart';


// 输出配置
// 控制台执行:dart  run pigeon --input pigeons/message.dart
@ConfigurePigeon(PigeonOptions(
  dartOut: './lib/messages.g.dart',
  dartPackageName: 'base_plugin',
  kotlinOut: 'android/src/main/kotlin/com/app/base_plugin/Messages.g.kt',
  kotlinOptions: KotlinOptions(
    // copyrightHeader: ['zero'],
    package: 'com.app.base_plugin',
  ),
  swiftOut: 'ios/Classes/Messages.g.swift',
  swiftOptions: SwiftOptions(),
))
@HostApi()
abstract class HostMessageApi {
  String flutter2Native(String message, int type);

  @async
  String flutter2NativeAsync(String message, int type);
}

@FlutterApi()
abstract class FlutterMessageApi {
  String native2Flutter(String message, int type);

  @async
  String native2FlutterAsync(String message, int type);
}
4. 执行生成各个平台文件的命令

dart run pigeon --input pigeons/message.dart

5. base_plugin.dart
dart 复制代码
import 'messages.g.dart';

class BasePlugin {
  static final HostMessageApi _api = HostMessageApi();
  static Future<String>  flutter2Native(String message, int type) async {
    return await _api.flutter2Native(message, type);
  }
  static Future<String>  flutter2NativeAsync(String message, int type) async {
    return await _api.flutter2NativeAsync(message, type);
  }
}
6. BasePlugin.kt
kt 复制代码
package com.app.base_plugin

import androidx.annotation.NonNull
import com.app.base_plugin.FlutterMessageApi
import com.app.base_plugin.HostMessageApi
import io.flutter.embedding.engine.plugins.FlutterPlugin


/** BasePlugin */
class BasePlugin: FlutterPlugin, HostMessageApi {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var flutterMessageApi: FlutterMessageApi
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        print("onAttachedToEngine")
        HostMessageApi.setUp(flutterPluginBinding.binaryMessenger, this)
        flutterMessageApi = FlutterMessageApi(flutterPluginBinding.binaryMessenger)
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        HostMessageApi.setUp(binding.binaryMessenger, null)
    }

    override fun flutter2Native(message: String, type: Long): String {
        print("flutter2Native=message=$message=type=$type")
        flutterMessageApi.native2Flutter("111", callback = {
            print("1111")
        }, typeArg = 1)
        return message
    }

    override fun flutter2NativeAsync(
        message: String,
        type: Long,
        callback: (Result<String>) -> Unit
    ) {
        fun  d(e:Result<String>){
            print("d")
        }
        print("flutter2NativeAsync=message=$message=type=$type")
        flutterMessageApi.native2FlutterAsync("2222", callback = {
            print("222")
        }, typeArg = 2)
        callback(Result.success("flutter2NativeAsync=message=$message=type=$type"));
    }
}
7. BasePlugin.swift
swift 复制代码
import Flutter
import UIKit

public class BasePlugin: NSObject, FlutterPlugin,HostMessageApi {
    
    private static var flutterAPI: FlutterMessageApi? = nil
    public static func register(with registrar: any FlutterPluginRegistrar) {
        let api = BasePlugin()
        HostMessageApiSetup.setUp(binaryMessenger: registrar.messenger(), api: api)
        flutterAPI = FlutterMessageApi(binaryMessenger: registrar.messenger())
    }
    
    func flutter2Native(message: String, type: Int64) throws -> String {
        print("ios->flutter2NativeMessage===="+message);
        return "ios->flutter2Native=message=\(message)=type=\(type)"
    }
    
    func flutter2NativeAsync(message: String, type: Int64, completion: @escaping (Result<String, any Error>) -> Void) {
        print("ios->flutter2NativeAsyncMessage===2")
        completion(.success(message))
    }

    

}
8. 遇到的问题

Parse Issue (Xcode): Module 'base_plugin' not found

  1. 删除ios文件下面的podfile和podfile.lock
  2. Messages.g.swift 和BasePlugin.swift 要放到Classes下面

Pigeon: error: type 'FlutterError' does not conform to protocol 'Error'

  1. 在Messages.g.swift中添加extension FlutterError: Swift.Error {}
9. 源码
相关推荐
一二小选手2 分钟前
【Java Web】分页查询
java·开发语言
大G哥2 分钟前
python 数据类型----可变数据类型
linux·服务器·开发语言·前端·python
卡卡_R-Python4 分钟前
子集选择——基于R语言实现(最优子集选择法、逐步回归法、Lasso回归法、交叉验证法)
回归·r语言·kotlin
Code成立16 分钟前
《Java核心技术 卷I》用户图形界面鼠标事件
java·开发语言·计算机外设
Xiao Fei Xiangζั͡ޓއއ36 分钟前
一觉睡醒,全世界计算机水平下降100倍,而我却精通C语言——scanf函数
c语言·开发语言·笔记·程序人生·面试·蓝桥杯·学习方法
记录无知岁月39 分钟前
【MATLAB】目标检测初探
开发语言·yolo·目标检测·matlab·yolov3·yolov2
远望清一色1 小时前
基于MATLAB身份证号码识别
开发语言·图像处理·算法·matlab
NMBG221 小时前
[JAVAEE] 面试题(四) - 多线程下使用ArrayList涉及到的线程安全问题及解决
java·开发语言·面试·java-ee·intellij-idea
Py小趴1 小时前
Python自学之Colormaps指南
开发语言·python·数据可视化
晒足以百八十1 小时前
基于Python 和 pyecharts 制作招聘数据可视化分析大屏
开发语言·python·信息可视化