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

简介: 用pigeon kotlin swift写一个自己的插件
1. 创建一个flutter plugin项目
2. 引入依赖

pigeon: ^18.0.0

3. 创建pigeons文件夹和message.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
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
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
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’


在Messages.g.swift中添加extension FlutterError: Swift.Error {}


相关文章
|
4月前
|
Swift iOS开发 Kotlin
苹果iOS新手开发之Swift中实现类似Kotlin的作用域函数
Swift可通过扩展实现类似Kotlin作用域函数效果。如自定义`let`, `run`, `with`, `apply`, `also`,增强代码可读性和简洁性。虽无直接内置支持,但利用Swift特性可达成相似功能。
71 7
|
6月前
|
安全 Swift Android开发
构建移动应用:Swift vs Kotlin —— 两大主流语言的对决
【5月更文挑战第11天】Swift与Kotlin在移动应用开发中各有优势。Swift是iOS开发的首选,以其简洁语法、高性能和类型安全著称;而Kotlin是Android的官方推荐语言,以其与Java的无缝互操作、空安全特性和简洁代码受到青睐。两者在语法简洁性、性能和社区支持上表现优秀,但平台兼容性不同。开发者应根据项目需求和目标平台选择合适的语言。
|
Android开发 Kotlin
kotlin新版本插件本地安装
kotlin新版本插件本地安装
|
XML Java 开发工具
使用 Kotlin 开发 Android 应用 | 8 个最优秀的 Android Studio 插件 Kotlin Android 素材
butterknife http://jakewharton.github.io/butterknife/ Annotate fields with @BindView and a view ID for Butter Knife to find an...
2039 0
|
Cloud Native 架构师 安全
Kotlin 异步框架 Ktor 2.0 发布,提供新的插件特性
Ktor 是一个用于创建异步客户端和服务器应用程序的Kotlin框架。经过 1 年多的开发,2.0版本于近日发布,在带来新特性的同时,也带来了破坏性的变化。
441 0
Kotlin 异步框架 Ktor 2.0 发布,提供新的插件特性
DHL
|
XML 缓存 算法
Kotlin 插件的落幕,ViewBinding 的崛起
我们看一下如何在项目中使用 DataBinding 和 ViewBinding,因文章篇幅原因,这里仅仅演示在 Activity 中使用,更多用法可以查看 Binding 库的示例。
DHL
466 0
Kotlin 插件的落幕,ViewBinding 的崛起
【JetPack】kotlin-android-extensions 插件 ( 视图绑定简单用法 )
【JetPack】kotlin-android-extensions 插件 ( 视图绑定简单用法 )
601 0
|
Java Maven Kotlin
使用 Kotlin , Groovy ,Java 开发一个自己的 Gradle 插件
使用 Kotlin , Groovy ,Java 开发一个自己的 Gradle 插件 先上效果图: image.png 功能说明: korGenerate: 自动生成 Entity,Dao,Controller 模板代码 ko...
1758 0
|
安全 Java Android开发