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");
  }
}
相关推荐
louisgeek8 小时前
Flutter StatelessWidget 和 StatefulWidget 的区别
flutter
不知名美食探索家8 小时前
【11】Redis快速安装与Golang实战指南
redis·golang·bootstrap
_一条咸鱼_9 小时前
Android 大厂面试秘籍:Hilt 框架的测试支持模块(八)
android·面试·kotlin
普通网友9 小时前
内置AI与浏览器的开源终端Wave Terminal安装与远程连接内网服务器教程
开发语言·后端·golang
JarvanMo9 小时前
Flutter插件中引用aar
flutter
行思理9 小时前
go语言应该如何学习
开发语言·学习·golang
returnShitBoy10 小时前
Go语言中的垃圾回收是如何工作的?
java·jvm·golang
普通网友11 小时前
如何在CentOS部署青龙面板并实现无公网IP远程访问本地面板
开发语言·后端·golang
虾米2025041112 小时前
使用 Kotlin 协程思考体会
kotlin
孤鸿玉12 小时前
[Flutter小试牛刀] 写一个低配版的signals
flutter