文章目录
为什么flutter要用go写工具类
在Flutter 应用中,有些场景涉及到大量的计算,比如复杂的加密算法、数据压缩 / 解压缩或者图形处理中的数学计算等
1. 下载pigeon插件模版
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
- Greeting.xcframework拷贝到base_plugin/ios
- 修改base_plugin.podspec
添加 s.vendored_frameworks = ‘Greeting.xcframework’- 修改ios/Classes/BasePlugin.swift
- 如果运行报错,就删除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
- 拷贝greeting.aar到android/libs/,没有libs就创建一个
- 修改android/build.gradle
- 修改BasePlugin.kt
- 新开一个窗口,打开插件下面的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");
}
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » flutter pigeon gomobile 插件中使用go工具类
发表评论 取消回复