文章目录
- 命令
- 引入greeting.aar和使用
- android中使用Flutter2gopluginPlugin.kt
- 参考文档
命令
mkdir demo
cd demo
go mod init demo
编写greeting.go
go env -w GOPROXY=https://goproxy.cn
go install golang.org/x/mobile/cmd/gomobile@latest
gomobile init
go get golang.org/x/mobile/bind
gomobile bind -target=android
会生成greeting.aar和greeting-sources.jar
greeting.go
package greeting
func SayHi(text string) string {return text
}
引入greeting.aar和使用
创建flutter插件
在android下面创建libs
复制greeting.aar到libs下面
配置android/build.gradle
group 'com.app.flutter2goplugin'
version '1.0-SNAPSHOT'buildscript {ext.kotlin_version = '1.7.10'repositories {google()mavenCentral()}dependencies {classpath 'com.android.tools.build:gradle:7.2.0'classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"}
}allprojects {repositories {google()mavenCentral()}
}apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'android {compileSdkVersion 31compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}kotlinOptions {jvmTarget = '1.8'}sourceSets {main.java.srcDirs += 'src/main/kotlin'}defaultConfig {minSdkVersion 16}
}rootProject.allprojects{repositories {google()mavenCentral()flatDir {dirs project(':flutter2goplugin').file('libs')}}
}dependencies {implementation(name: "greeting", ext: "aar")
}
android中使用Flutter2gopluginPlugin.kt
package com.app.flutter2gopluginimport android.util.Log
import androidx.annotation.NonNull
import greeting.Greetingimport io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Resultclass Flutter2gopluginPlugin : FlutterPlugin, MethodCallHandler {private lateinit var channel: MethodChanneloverride fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter2goplugin")channel.setMethodCallHandler(this)}override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {if (call.method == "getPlatformVersion") {Log.e("getPlatformVersion", Greeting.sayHi("bbbbbbbbbbb"))result.success("Android ${android.os.Build.VERSION.RELEASE}")} else {result.notImplemented()}}override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {channel.setMethodCallHandler(null)}
}
参考文档
完整流程 Flutter 集成 Golang 多语言跨端开发基础案例