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

文章目录

为什么flutter要用go写工具类

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

1. 下载pigeon插件模版

base_plugin

2. 编写go代码
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
podspec 复制代码
#
# 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
swift 复制代码
//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代码
grdle 复制代码
//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_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中使用
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});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp>  implements FlutterMessageApi{
  String _platformVersion = 'Unknown';
  final _basePlugin = BasePlugin();

  @override
  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;
    });
  }

  @override
  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("调用插件方法"))
          ],
        ),
      ),
    );
  }

  @override
  String native2Flutter(String message, int type) {
    print("native2Flutter=$message $type");
    return "native2Flutter=$message";
  }

  @override
  Future<String> native2FlutterAsync(String message, int type) {
    print("native2FlutterAsync=$message  $type");
    return Future(() => "native2FlutterAsync=$message");
  }
}
相关推荐
Clown952 小时前
go-zero(四) 错误处理(统一响应信息)
开发语言·golang·lua
hummhumm2 小时前
第 17 章 - Go语言 上下文( Context )
java·服务器·网络·后端·python·sql·golang
ahhhhaaaa-2 小时前
【AI图像生成网站&Golang】图床上传与图像生成API搭建
开发语言·人工智能·golang
iOS阿玮3 小时前
Appstore的产品突然被下架,还是4.3(a)?
swift·apple
H_kiwi3 小时前
APT 参与者将恶意软件嵌入 macOS Flutter 应用程序中
java·python·安全·flutter·macos·安全威胁分析·安全性测试
fcopy4 小时前
Golang云原生项目:—实现ping操作
开发语言·golang
Clown954 小时前
go-zero(二) api语法和goctl应用
开发语言·后端·golang
Python私教4 小时前
go语言中的占位符有哪些
开发语言·后端·golang
007php0074 小时前
使用 Go 实现将任何网页转化为 PDF
开发语言·后端·python·docker·chatgpt·golang·pdf