flutter集成到安卓并实现交互

一、

1、用androidstudio,在file->new->new module->flutter module
建议放在安卓项目的同级文件夹里,androidstudio会自动配置flutter模块,要注意的是在安卓项目的settings.gradle里include的必须是“app”!如下图


图片.png

2、用终端创建 Flutter modul(集成到原生项目)不推荐

flutter create --template module my_flutter

二、在安卓app的build gradle的android {}中添加代码

图片.png
compileOptions {
    sourceCompatibility 1.8
    targetCompatibility 1.8
}
//可酌情添加,我这边感觉没啥卵用
defaultConfig {
    ndk {
        // Filter for architectures supported by Flutter.
        abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64'
    }
}

//dependencies {}引入头文件

implementation project(':flutter')

三、添加组件

在AndroidManifest.xml的<application中

    android:name="io.flutter.embedding.android.FlutterActivity"
    android:theme="@style/Theme.AppCompat.NoActionBar"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize"
    />

四、最重要的交互来了,在需要跳转的界面中做交互(文档上在MainActivity.java中交互,那样数据还需要传,麻烦)

引入头文件

import io.flutter.embedding.android.FlutterActivity;

//预加载flutterEngine,跳转时候不白屏

//flutter与原生回调
    public void jumpflutterPlugn ()
    {
        flutterEngine = new FlutterEngine(this);
        flutterEngine.getDartExecutor().executeDartEntrypoint(
                DartExecutor.DartEntrypoint.createDefault()
        );
        FlutterEngineCache
                .getInstance()
                .put("my_engine_id", flutterEngine);
//MethodChannel关联flutterEngine,好做回调
channel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),CHANNEL);
channel.setMethodCallHandler(  (call, result) -> {
    if (call.method.equals("iOSFlutter2"))
    {
//安卓通过回调的方式,往flutter
 传递参数,注意⚠️参数类型只能是字符串
//解决问题[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: MissingPluginException(No implementation found for method iOSFlutterQiantui on channel wg/native_get
       String jsonString = GsonUtil.GsonString(suoyoudict);
        result.success(jsonString);
}else if (call.method.equals("iOSFlutterCunChuDanJu")) {
    //flutter回调传参
    Map<String,Object> danjudict = new HashMap();
    danjudict=call.arguments();
    handleSKD(danjudict);
}
});
    }

在此遇到诸多问题以及解决方式或者链接我挑选了一部分写在末尾,给后来者做参考

1、AndroidX的问题:集成flutter_module报错,找不到符号,AndroidX兼容问题如何解决?

gradle.properties中
android.useAndroidX=true
android.enableJetifier=true

https://coding.imooc.com/learn/questiondetail/131836.html

2、flutter降低版本禁用AndroidX方式

https://www.sohu.com/a/336423659_671494

3、解决annotations-13.0.jar包重复问题

//在安卓app的build gradle的android {}中添加代码
  configurations {
        cleanedAnnotations
        compile.exclude group: 'org.jetbrains' , module:'annotations'
    }

4、空安全问题。最好是做好空安全的处理,去除掉没有适配空安全的第三方插件,再在自己的flutter代码里适配空安全,很简单,按照提示来就行。当然如果嫌麻烦的话,可以试试下面命令

flutter run --no-sound-null-safety

推荐阅读更多精彩内容