Flutter 可以作为单独的app存在,也可以在Android或者ios中以页面部分存在或者以局部来存在,当然就是涉及到Android原生程序和Flutter程序之间的通信。
大致步骤如下:
因为涉及两种不同类型的项目进行关联和通信,因为需要先创建两个项目,Android项目和Flutter要存放到相同文件夹下。
- Flutter_hybrid
- Flutter_module
- FlutterHybridAndroid
- FlutterHybridioS
@H_502_8@2.Android项目配置
- android module 使用java1.8
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
setBinding(new Binding([gradle: this])) // new
evaluate(new File( // new
settingsDir.parentFile, // new
'Flutter_module/.android/include_Flutter.groovy' // new
))
implementation project(':Flutter')
@H_502_8@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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。