背景:
在很多场景Flutter项目需要使用到Plugin集成原生SDK,做过Android开发的同学对aar都很熟悉,就是android library编译出来的产物
如果在flutter中直接集成aar会怎样呢?先来试一下
步骤:
1,创建Flutter Application工程 2,创建Flutter Plugin(这里直接放到Application工程中,新建plugin目录在plugin创建)
3,在plugin工程的Android项目里面放入aar sdk 4,配置plugin中Android项目的build.gradle文件
implementation fileTree(include: ['*.aar'], dir: 'libs')
/** MavenAarPlugin */
public class MavenAarPlugin implements FlutterPlugin, MethodCallHandler {
/// 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 MethodChannel channel;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "maven_aar_plugin");
channel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
//引入aar sdk中的代码
ProcessPhoenix.triggerRebirth(binding.getApplicationContext());
}
}
至此就可以开始运行了,运行报错如下: Direct local .aar file dependencies are not supported when building an AAR. The resulting AAR would be broken because the classes and Android resources from any local .aar file dependencies would not be packaged in the resulting AAR. Previous versions of the Android Gradle Plugin produce broken AARs in this case too (despite not throwing this error). The following direct local .aar file dependencies of the :maven_aar_plugin project caused this error 报错原因就是aar中不能有aar,这个跟android工程的编译有关,Flutter Plugin中的Android也会被编译成aar,那为什么Flutter/Native混合集成开发中不会出现这个报错?因为混合工程会把Flutter Plugin中的Android项目当作原生的library编译,而Flutter Application的编译流程可以去查看$flutterRoot/packages/flutter_tools/gradle/flutter.gradle下的文件,它的编译过程不会合并aar
解决方案
问题原因找到了解决方案那么也很简单 1,把aar解压成jar包放到lib下,从aar依赖变成jar依赖这样就不会报错了 2,使用maven依赖,把aar上传到maven。这样打包的时候aar也不会在lib文件夹中 3,使用fat-aar插件,他的原理也是将aar解压然后合并 打开Flutter Plugin工程下Android的build.gradle文件
group 'com.aar.maven.maven_aar_plugin'
version '1.0'
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
//1 依赖classpath
classpath 'com.kezong:fat-aar:1.3.3'
}
}
rootProject.allprojects {
repositories {
google()
jcenter()
}
}
apply plugin: 'com.android.library'
//导入插件,注意顺序,放在com.android.librar下面
apply plugin: 'com.kezong.fat-aar'
android {
compileSdkVersion 30
defaultConfig {
minSdkVersion 16
}
}
dependencies {
//把implementation修改成embed
embed fileTree(include: ['*.aar'], dir: 'libs')
}
这个时候再次运行就OK了
|