用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. 源码
相关推荐
波音彬要多做19 分钟前
41 stack类与queue类
开发语言·数据结构·c++·学习·算法
Swift社区27 分钟前
Excel 列名称转换问题 Swift 解答
开发语言·excel·swift
一道微光31 分钟前
Mac的M2芯片运行lightgbm报错,其他python包可用,x86_x64架构运行
开发语言·python·macos
矛取矛求35 分钟前
QT的前景与互联网岗位发展
开发语言·qt
Leventure_轩先生35 分钟前
[WASAPI]从Qt MultipleMedia来看WASAPI
开发语言·qt
向宇it1 小时前
【从零开始入门unity游戏开发之——unity篇01】unity6基础入门开篇——游戏引擎是什么、主流的游戏引擎、为什么选择Unity
开发语言·unity·c#·游戏引擎
是娜个二叉树!1 小时前
图像处理基础 | 格式转换.rgb转.jpg 灰度图 python
开发语言·python
Schwertlilien1 小时前
图像处理-Ch5-图像复原与重建
c语言·开发语言·机器学习
liuyunshengsir1 小时前
Squid代理服务器的安装使用
开发语言·php
只做开心事1 小时前
C++之红黑树模拟实现
开发语言·c++