一、创建Flutter Module
在已有Android工程中集成flutter,可以使用AndroidStudio的new Flutter Module实现,方便快捷。

找到FlutterModule,一连串的next操作即可
创建完成后我们的项目中会多一个叫做flutter的module
并且在项目的setting.gradle文件中会自动添加如下几行代码,
setBinding(new Binding([gradle:this]))evaluate(new File(settingsDir,'flutter_module/.android/include_flutter.groovy'))include ':flutter_module'
最后我们只需在app的build.gradle中引用这个flutter模块即可
implementation project(path: ':flutter')
二、使用Flutter
两种使用方式,FlutterView和FlutterFragment。
1、使用FlutterFragment
新版本的FlutterSDK不再支持已经没有Flutter类,不再支持诸如Flutter.createView()、Flutter.createFragment()等用法,通过阅读其源码我们可以找到FlutterFragment的新用法,代码如下:
public class MyFlutterActivity extends FragmentActivity {@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.flutter_layout);//FlutterFragment fragment=new FlutterFragment();FlutterFragment fragment=FlutterFragment.withNewEngine().initialRoute("home").build();getSupportFragmentManager().beginTransaction().add(R.id.flutter_container, fragment).commit();}}
代码中FlutterFragment的创建也可以直接使用默认的构造方法,这样加载main.dart中的默认路由,即’’/‘’,给出的示例代码中我们通过调用FlutterFragment.withNewEngine().initialRoute("home").build()创建了新的NewEngineFragmentBuilder来构建指定路由的FlutterFragment。
2、使用FlutterView
FlutterView的创建同样不能使用老版本的方法了,新版本的使用方法代码如下:
public class MyFlutterActivity extends FragmentActivity {@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.flutter_layout);FrameLayout frameLayout=findViewById(R.id.flutter_container);ProgressBar progress=findViewById(R.id.progress);//创建FlutterViewFlutterView flutterView=new FlutterView(this);//创建FlutterView首帧渲染完成监听flutterView.addFirstFrameListener(new FlutterView.FirstFrameListener() {@Overridepublic void onFirstFrame() {//隐藏进度条,显示FlutterViewprogress.setVisibility(View.GONE);frameLayout.setVisibility(View.VISIBLE);}});//创建dart代码执行器DartExecutor executor=flutterView.getDartExecutor();//执行main.dart中的main函数executor.executeDartEntrypoint(new DartExecutor.DartEntrypoint(FlutterMain.findAppBundlePath(),"main"));//将FlutterView添加到布局中ViewGroup.LayoutParams layoutParams=new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);frameLayout.addView(flutterView);}}
布局文件如下:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><FrameLayoutandroid:id="@+id/flutter_container"android:visibility="invisible"android:layout_width="match_parent"android:layout_height="match_parent"></FrameLayout><ProgressBarandroid:id="@+id/progress"android:layout_width="45dp"android:layout_height="45dp"android:layout_centerVertical="true"android:layout_centerHorizontal="true"android:visibility="visible"></ProgressBar></RelativeLayout>
效果如下图
