flutter 可以作为单独的app存在,也可以在Android或者ios中以页面部分存在或者以局部来存在,当然就是涉及到Android原生程序和flutter程序之间的通信。
大致步骤如下:
1.创建Flutter_module项目
因为涉及两种不同类型的项目进行关联和通信,因为需要先创建两个项目,Android项目和flutter要存放到相同文件夹下。
- flutter_hybrid
- flutter_module
- FlutterHybridAndroid
- FlutterHybridiOS
2.Android项目配置
- android module 使用java1.8
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
- 最低Android 版本16
- setting文件要配置flutter_module项目
setBinding(new Binding([gradle: this])) // new
evaluate(new File( // new
settingsDir.parentFile, // new
'flutter_module/.android/include_flutter.groovy' // new
))
implementation project(':flutter')
3.关联对象
到这里我们就开始编写Android项目的code,写之前先看效果图。点击按钮,会把flutter的界面调取处理展示。
主界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="展示flutter!"
/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/content"
/>
</LinearLayout>
代码逻辑:
备注:FlutterFragment其实就是一个fragment,在这里注意Flutter_module是否使用了androidx版本,因为这会影响fragment的版本,是v4还是androidx,这里会导致找不到匹配类型。原则就是两个项目要统一一个版本。
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.click:
// TODO 20/02/05
//点击按钮,使用FlutterFragment替换掉占位布局,
final FlutterFragment fragment = Flutter.createFragment("content");
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content, fragment ).commit();
break;
default:
break;
}
}
总结:这里Android和flutter结合使用Flutter.createFragment,这种形式就是把flutter的逻辑封装成一个fragment,因为fragment轻量化,灵活的特点,可以作为页面,也可以作为局部存在。
还有一种形式就是Flutter.createView(this, getLifecycle(), “content”);它创建了一个view,展示到Android原生界面里,这里面一共三个参数:
- this 上下文context
- lifecycle 生命周期的对象,可以根据生命周期,处理各种状态的逻辑
- initalRoute 初始化路由,相当于在展示页面或者是跳转的时候,可以初始化一些数据或者指定就是不同的页面。
final FlutterView flutterView = Flutter.createView(this, getLifecycle(), "content");
mContent.removeAllViews();
mContent.addView(flutterView);