flutter pigeon gomobile 插件中使用go工具类

server/2024/11/20 2:53:02/

文章目录

        • 为什么flutter要用go写工具类
        • 1. 下载pigeon插件模版
        • 2. 编写go代码
        • 3.生成greeting.aar,Greeting.xcframework
        • 4. ios
        • 5. android
        • 6. dart中使用

fluttergo_1">为什么flutter要用go写工具类

在Flutter 应用中,有些场景涉及到大量的计算,比如复杂的加密算法、数据压缩 / 解压缩或者图形处理中的数学计算等

1. 下载pigeon插件模版

base_plugin

2. 编写go代码
//greeting.go
package greetingimport "fmt"func SayHi(text string) string {return text
}
func Hello(name string) {fmt.Printf("Hello %s!\n", name)
}
3.生成greeting.aar,Greeting.xcframework

gomobile bind -target=ios
gomobile bind -target=android -androidapi 26
go get golang.org/x/mobile/bind/objc (可选)
go get golang.org/x/mobile/bind (可选)

4. ios
  1. Greeting.xcframework拷贝到base_plugin/ios
  2. 修改base_plugin.podspec
    添加 s.vendored_frameworks = ‘Greeting.xcframework’
  3. 修改ios/Classes/BasePlugin.swift
  4. 如果运行报错,就删除build
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint base_plugin.podspec` to validate before publishing.
#
Pod::Spec.new do |s|s.name             = 'base_plugin's.version          = '0.0.1's.summary          = 'A new Flutter project.'s.description      = <<-DESC
A new Flutter project.DESCs.homepage         = 'http://example.com's.license          = { :file => '../LICENSE' }s.author           = { 'Your Company' => 'email@example.com' }s.source           = { :path => '.' }s.source_files = 'Classes/**/*'s.dependency 'Flutter's.platform = :ios, '11.0'# Flutter.framework does not contain a i386 slice.s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }s.swift_version = '5.0'# 添加框架路径s.vendored_frameworks = 'Greeting.xcframework'
end
swift">//BasePlugin.swift
import Flutter
import UIKit
import Greeting
public class BasePlugin: NSObject, FlutterPlugin,HostMessageApi {private static var flutterAPI: FlutterMessageApi? = nilpublic 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->flutter2Native=>start=>message=\(message)=type=\(type)");if type==1 {GreetingHello("调用hello")return "GreetingHello"} else if type==2{return GreetingSayHi("调用SayHi")}else{return "ios->flutter2Native=>start=>message=\(message)=type=\(type)"}}func flutter2NativeAsync(message: String, type: Int64, completion: @escaping (Result<String, any Error>) -> Void) {print("ios->flutter2NativeAsyncMessage===2")completion(.success(message))}}
5. android
  1. 拷贝greeting.aar到android/libs/,没有libs就创建一个
  2. 修改android/build.gradle
  3. 修改BasePlugin.kt
  4. 新开一个窗口,打开插件下面的example下面的android项目,方便修改BasePlugin.kt代码
//build.gradle
rootProject.allprojects {repositories {google()mavenCentral()flatDir {dirs project(':base_plugin').file('libs')}}
}
dependencies {implementation(name: "greeting", ext: "aar")
}
kotlin">//BasePlugin.kt
package com.app.base_pluginimport androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import greeting.Greeting/** 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 Activityprivate lateinit var flutterMessageApi: FlutterMessageApioverride 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=start=>$message=type=$type")flutterMessageApi.native2Flutter("input params=>2222", callback = {print("response=>${it.getOrNull()}")}, typeArg = 1)when (type) {1L -> {Greeting.Hello("111111")return "Greeting.Hello"}2L -> {return Greeting.sayHi("flutter2Native=message=$message=type=$type")}else -> {return "flutter2Native=message=$message=type=$type"}}}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"));}
}
6. dart中使用
import 'package:base_plugin/base_plugin.dart';
import 'package:base_plugin/messages.g.dart';
import 'package:flutter/material.dart';
import 'dart:async';import 'package:flutter/services.dart';void main() {runApp(const MyApp());
}class MyApp extends StatefulWidget {const MyApp({super.key});State<MyApp> createState() => _MyAppState();
}class _MyAppState extends State<MyApp>  implements FlutterMessageApi{String _platformVersion = 'Unknown';final _basePlugin = BasePlugin();void initState() {super.initState();initPlatformState();FlutterMessageApi.setUp(this);}// Platform messages are asynchronous, so we initialize in an async method.Future<void> initPlatformState() async {String platformVersion;// Platform messages may fail, so we use a try/catch PlatformException.// We also handle the message potentially returning null.try {platformVersion =await BasePlugin.flutter2Native("33344", 0);} on PlatformException {platformVersion = 'Failed to get platform version.';}// If the widget was removed from the tree while the asynchronous platform// message was in flight, we want to discard the reply rather than calling// setState to update our non-existent appearance.if (!mounted) return;setState(() {_platformVersion = platformVersion;});}Widget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: const Text('Plugin example app'),),body: Column(children: [Text('Running on: $_platformVersion\n'),TextButton(onPressed: () async {final result =await BasePlugin.flutter2Native("33344", 0);print("flutter2Native=$result");}, child: const Text("调用插件方法"))],),),);}String native2Flutter(String message, int type) {print("native2Flutter=$message $type");return "native2Flutter=$message";}Future<String> native2FlutterAsync(String message, int type) {print("native2FlutterAsync=$message  $type");return Future(() => "native2FlutterAsync=$message");}
}

http://www.ppmy.cn/server/143358.html

相关文章

基于Redis实现延时任务

在 Redis 中实现延时任务的功能主要有两种方案&#xff1a;Redis 过期事件监听和 Redisson 内置的延时队列。下面将详细解释这两种方案的原理、优缺点以及面试时需要注意的相关细节。 方案 1&#xff1a;Redis 过期事件监听 实现原理 Redis 从 2.0 版本开始支持**发布/订阅&a…

Argo workflow 拉取git 并使用pvc共享文件

文章目录 拉取 Git 仓库并读取文件使用 Kubernetes Persistent Volumes&#xff08;通过 volumeClaimTemplates&#xff09;以及任务之间如何共享数据 拉取 Git 仓库并读取文件 在 Argo Workflows 中&#xff0c;如果你想要一个任务拉取 Git 仓库中的文件&#xff0c;另一个任…

Upload-Labs-Linux1学习笔迹 (图文介绍)

lab 1 前端绕过jpg&#xff0c;后端改php后缀&#xff0c;通过蚁剑连接&#xff0c;在根目录下找到flag&#xff0c; flag{71dc5328-c145-4fbf-a987-4dfb4c1dacd1} //写以下文件a.jpgGIF89 <?php eval($_POST[cmd]); ?> labs 2 $is_upload false; $msg null; if …

工业大数据分析与应用:开启智能制造新时代

在全球工业4.0浪潮的推动下&#xff0c;工业大数据分析已经成为推动智能制造、提升生产效率和优化资源配置的重要工具。通过收集、存储、处理和分析海量工业数据&#xff0c;企业能够获得深刻的业务洞察&#xff0c;做出更明智的决策&#xff0c;并实现生产流程的全面优化。本文…

51c自动驾驶~合集27

我自己的原文哦~ https://blog.51cto.com/whaosoft/11989373 #无图NOA 一场对高精地图的祛魅&#xff01;2024在线高精地图方案的回顾与展望~ 自VectorMapNet以来&#xff0c;无图/轻图的智能驾驶方案开始出现在自动驾驶量产的牌桌上&#xff0c;到如今也有两年多的时间。而…

蓝桥杯每日真题 - 第12天

题目&#xff1a;&#xff08;数三角&#xff09; 题目描述&#xff08;14届 C&C B组E题&#xff09; 解题思路&#xff1a; 给定 n 个点的坐标&#xff0c;计算其中可以组成 等腰三角形 的三点组合数量。 核心条件&#xff1a;等腰三角形的定义是三角形的三条边中至少有…

pytest结合allure做接口自动化

这是一个采用pytest框架&#xff0c;结合allure完成接口自动化测试的项目&#xff0c;最后采用allure生成直观美观的测试报告&#xff0c;由于添加了allure的特性&#xff0c;使得测试报告覆盖的内容更全面和阅读起来更方便。 1. 使用pytest构建测试框架&#xff0c;首先配置好…

游戏引擎学习第九天

视频参考:https://www.bilibili.com/video/BV1ouUPYAErK/ 修改之前的方波数据&#xff0c;改播放正弦波 下面主要讲关于浮点数 1. char&#xff08;字符类型&#xff09; 大小&#xff1a;1 字节&#xff08;8 位&#xff09;表示方式&#xff1a;char 存储的是一个字符的 A…