当前位置: 首页 > article >正文

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

文章目录

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

为什么flutter要用go写工具类

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

1. 下载pigeon插件模版

base_plugin

2. 编写go代码
//greeting.go
package greeting

import "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.
                       DESC
  s.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

//BasePlugin.swift
import Flutter
import UIKit
import Greeting
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->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")
}

//BasePlugin.kt
package com.app.base_plugin

import 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 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=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.kler.cn/a/400186.html

相关文章:

  • PhpSpreadsheet导出图片
  • MyBatis-Plus中使用JSON 类型字段
  • SpringSecurity+jwt+captcha登录认证授权总结
  • 使用nossl模式连接MySQL数据库详解
  • 华为HCIP——MSTP/RSTP与STP的兼容性
  • 【MySQL】MySQL数据库入门:构建你的数据基石
  • 基于css的Grid布局和vue实现点击左移右移轮播过渡动画效果
  • 【Patroni官方文档】复制模式
  • STM32 使用 STM32CubeMX HAL库实现低功耗模式
  • PCL 三维重建 泊松曲面重建算法
  • AIGC(生成式AI)试用 18 -- AI Prompt
  • World Wide Walrus:下一代数据存储协议
  • 【C++学习(36)】C++20的co_await 的不同使用方式和特性
  • Cellebrite VS IOS18Rebooting
  • 建设项目全生命周期数智化归档与协同管理平台
  • 【第七课】Rust所有权系统(三)
  • React|bpmn.js|react-bpmn使用示例详解
  • STARTS:一种用于自动脑电/脑磁(E/MEG)源成像的自适应时空框架|文献速递-基于深度学习的病灶分割与数据超分辨率
  • 区块链中的wasm合约是什么?
  • 主界面获取个人信息测试服务端方
  • 第6章-详细设计 6.4归一化
  • Verilog HDL学习笔记
  • JDK、MAVEN与IDEA的安装与配置
  • pytorch的模型load
  • C语言练习.if.else语句
  • 全新UI H5购物商城系统存在前台任意文件上传漏洞