1.假设你已经熟悉flutter 开发熟悉dart 语言 android 原生开发技能
一、在安卓原生项目添加代码
1.创建示例布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:id="@+id/btn_openPage"
android:text="点开flutter页面"
android:onClick="openPage"
android:layout_height="wrap_content">
</Button>
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/ll"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
</LinearLayout>
2.native页面activity 创建
跳转掉flutter页面这里没啥说的,会安卓原生开发的都懂
public void openPage(View view) {
startActivity(new Intent(this, MainActivity.class));
}
3.把flutter 页面装载到上面 LinearLayout里面加载flutter写的页面
1. 关联上面LinearLayout
FlutterView flutterView = new FlutterView(this);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout flContainer = findViewById(R.id.ll);
flContainer.addView(flutterView, lp);
2.flutterView.attachToFlutterEngine(flutterEngine);
flutterEngine = new FlutterEngine(this);
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
flutterView.attachToFlutterEngine(flutterEngine);
3.以上执行并不会显示加载fluuter页面的内容需要引擎关联页面的生命周期
@Override
protected void onResume() {
super.onResume();
flutterEngine.getLifecycleChannel().appIsResumed();
}
@Override
protected void onPause() {
super.onPause();
flutterEngine.getLifecycleChannel().appIsInactive();
}
@Override
protected void onStop() {
super.onStop();
flutterEngine.getLifecycleChannel().appIsPaused();
}
总结、通过上面的步骤就可以显示flutter页面内容如图
另外还有几种方法可以实现
1、FlutterFragment
FlutterFragment flutterFragment = FlutterFragment.createDefault();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.ll, flutterFragment)
.commit();
2.FlutterFragment.withNewEngine()
FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
.initialRoute("route1")
.build();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.ll, flutterFragment)
.commit();
3.FlutterFragment.withCachedEngine
FlutterEngine flutterEngine = new FlutterEngine(this);
flutterEngine.getNavigationChannel().setInitialRoute("route1");
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine);
// 通过FlutterFragment引入Flutter编写的页面
FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
.build();