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");
  }
}
相关推荐
打工人你好7 小时前
Swift 的 KeyPath 是什么?
swift
赵琳琅7 小时前
Java语言的云计算
开发语言·后端·golang
赵琳琅7 小时前
MDX语言的安全开发
开发语言·后端·golang
夏梓蕙8 小时前
Elixir语言的软件开发工具
开发语言·后端·golang
夏梓蕙8 小时前
R语言的Web开发
开发语言·后端·golang
yzpyzp9 小时前
kotlin中RxHttp的toAwaitResponse和awaitResult函数的使用
android·kotlin
恋猫de小郭10 小时前
Flutter 正在推进全新 PlatformView 实现 HCPP, 它又用到了 Android 上的什么黑科技
android·科技·flutter
慕容秋瑶10 小时前
T-SQL语言的Web开发
开发语言·后端·golang
帅次12 小时前
Flutter 异步编程利器:Future 与 Stream 深度解析
android·flutter·ios·小程序·kotlin·webview·android-studio
柯木超12 小时前
深入解析 Flutter Widget 树与布局:从电商首页到性能优化
flutter