一、背景

近期在做Android项目转型为Flutter,在转型的过程中,我们选择的是各业务模块逐各替换的方式。这种方式下必然会涉及到Android与Flutter的交互,而阿里提供的flutter_boost就是交互之作。

二、demo介绍

github:https://github.com/zbyJade/AndroidWithFlutter.git
如果下载后请进行如下操作

frc 71d9c942ef29ceed4a1bddb8ae3f802c - Android与Flutter混合开发之flutter_boost
image.png

如果还报错请重启

frc 4bfb4816a439ae770dfe46b6312e977a - Android与Flutter混合开发之flutter_boost
image.png

功能介绍:

  1. Android原生界面跳转Flutter界面,并传参
  2. Flutter界面跳转Android原生界面,并传参
  3. Android和Flutter在同一界面显示

    frc f2dce42783f2d5cd8a1a8f756e712b52 - Android与Flutter混合开发之flutter_boost
    1.jpg
frc d1d7744770514f7d2507a5871b12266f - Android与Flutter混合开发之flutter_boost
2.jpg
frc 56242c93dbe082772a7b8530d26c8b00 - Android与Flutter混合开发之flutter_boost
3.jpg
frc cfb6b1145eb6abfc491cfba3599b249a - Android与Flutter混合开发之flutter_boost
4.jpg

三、创建flutter_module

1.为了使demo代码简洁,新建一个Android工程,我用的是AS 3.6.3
frc dd37dcea2bf1816dde9b3a3d67b5d811 - Android与Flutter混合开发之flutter_boost
image.png

frc 8409bd500ae37d57cd4b10d7ab5e10a5 - Android与Flutter混合开发之flutter_boost
image.png
2.新建flutter module
frc 1914e9d6dac2061e931703ead3b875e6 - Android与Flutter混合开发之flutter_boost
image.png

frc deb95a5ce8e3a634e2ec3a369a7cd3f6 - Android与Flutter混合开发之flutter_boost
image.png

Project location 建议选择到你的Android project下,这样较清晰

frc e9ff04eb666707efac8f23d47080ed50 - Android与Flutter混合开发之flutter_boost
image.png

frc 511804b7c379d7a8e3c513209f2b5537 - Android与Flutter混合开发之flutter_boost
image.png
3.添加配置(AS 3.6会自动生成)

Project Settings

evaluate(new File(
  settingsDir,
  'flutter_module/.android/include_flutter.groovy'
))

include ':flutter_module'

app build.grade

implementation project(path: ':flutter')
4.创建module后,产生的问题和解决办法(如果没有出现更好)

问题1:该Wring可忽略

frc be540bae4d3928b0be950e6b1824805f - Android与Flutter混合开发之flutter_boost
image.png

问题2:

frc cb9498d52b4da8c7cba293b9a66ecc14 - Android与Flutter混合开发之flutter_boost
image.png

定位到问题文件,可删除框内文件

frc 59532a9cf074d79af9584c7922436cbd - Android与Flutter混合开发之flutter_boost
image.png

四、依赖flutter_boost

https://pub.dev/

frc 84044fa7010a3abf76b22594ac334038 - Android与Flutter混合开发之flutter_boost
image.png

如果你使用了Androidx找到兼容的版本

frc a6b0b1cb96c50a05bf4eb32e9f06df32 - Android与Flutter混合开发之flutter_boost
image.png

添加flutter_boost最新依赖

frc fbfac26cb8a7d0179424979af47e26ed - Android与Flutter混合开发之flutter_boost
image.png

实现过程如下

flutter_boost: ^1.12.13+1
frc 08d6548a4635b1f528bc2d2d1d07c2bc - Android与Flutter混合开发之flutter_boost
image.png

frc 91b5e6420fd0045ffb93846482688ac3 - Android与Flutter混合开发之flutter_boost
image.png

如果要是没有出现flutter和flutter_boost的module就稍微等一会

frc 08cc4cb18004cea251365dd206793b33 - Android与Flutter混合开发之flutter_boost
image.png

添加module

frc a4d7e109adbf6916ddea32d15aae1948 - Android与Flutter混合开发之flutter_boost
image.png

frc f0ff7037ad265164c9f1a3669644663c - Android与Flutter混合开发之flutter_boost
image.png

五、使用flutter_boost

5.1 封装PageRouter,界面跳转的路由工具类

public class PageRouter {
    // 界面格式可自定义
    public final static String OnePageUrl = "url://onePage";
    public final static String NativePage = "url://nativePage";

    public final static Map pageName = new HashMap() {{
        put(OnePageUrl, "onePage");
    }};


    public static boolean openPageByUrl(Context context, String url, Map params) {
        return openPageByUrl(context, url, params, 0);
    }

    public static boolean openPageByUrl(Context context, String url, Map params, int requestCode) {
        String flutterPage = null;
        if (url.startsWith(OnePageUrl)) {
            flutterPage = pageName.get(OnePageUrl);
            Intent intent = BoostFlutterActivity.withNewEngine().url(flutterPage).params(params)
                    .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context);
            context.startActivity(intent);
            return true;
        } else if (url.startsWith(NativePage)) {
            String aNative = (String) params.get("native");
            Bundle bundle = new Bundle();
            bundle.putString("native", aNative);
            context.startActivity(new Intent(context, NativePageActivity.class).putExtras(bundle));
            return true;
        }
        return false;
    }
}

5.2 Application中初始化(记着在AndroidManifest里引入BaseApplication)

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化
        initFlutterBoost();
    }

    private void initFlutterBoost() {
        Platform platform = new FlutterBoost.ConfigBuilder(this, new INativeRouter(){

            @Override
            public void openContainer(Context context, String url, Map urlParams, int requestCode, Map exts) {
                String assembleUrl = Utils.assembleUrl(url, urlParams);
                PageRouter.openPageByUrl(context, assembleUrl, urlParams);
            }
        }).isDebug(true)
                .whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
                .build();

        FlutterBoost.instance().init(platform);
    }
}

5.3 声明BoostFlutterActivity

   
        

5.4 activity跳转flutter界面,并传递参数

  findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 将map传递到flutter界面
                HashMap params = new HashMap();
                params.put("OneKey","从Android跳转到Flutter界面");
                PageRouter.openPageByUrl(MainActivity.this, PageRouter.OnePageUrl, params);
            }
        });

5.5 flutter界面跳转activity,并传递参数

 children: [
            // 如果接收到参数则显示,OneKey为传递map中的key
            Text(widget.param == null ? "未接收到参数" : widget.param["OneKey"]),
            RaisedButton(
                child: Text("调回Android界面"),
                onPressed: () {
                  // url://nativePage为PageRouter界面定义的,flutter调起Android界面
                  FlutterBoost.singleton.open("url://nativePage",
                      urlParams: {"native": "我是参数乙"});
                }),
            RaisedButton(
                child: Text("关闭当前界面"),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
          ],

5.6 Android和flutter混合界面

public class NativeAndFlutterActivity extends AppCompatActivity implements SplashScreenProvider {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_native_and_flutter);
        // 将flutter界面作为fragment添加到FrameLayout上
        FlutterFragment mFragment = new FlutterFragment.NewEngineFragmentBuilder().url("fragmentPage").build();
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_stub, mFragment)
                .commit();
    }

    @Override
    public SplashScreen provideSplashScreen() {
        // 为显示加载loading
        Drawable manifestSplashDrawable = getSplashScreenFromManifest();
        if (manifestSplashDrawable != null) {
            return new DrawableSplashScreen(manifestSplashDrawable, ImageView.ScaleType.CENTER, 500L);
        } else {
            return null;
        }
    }

    protected static final String SPLASH_SCREEN_META_DATA_KEY = "io.flutter.embedding.android.SplashScreenDrawable";
    private Drawable getSplashScreenFromManifest() {
        try {
            @SuppressLint("WrongConstant") ActivityInfo activityInfo = getPackageManager().getActivityInfo(
                    getComponentName(),
                    PackageManager.GET_META_DATA | PackageManager.GET_ACTIVITIES
            );
            Bundle metadata = activityInfo.metaData;
            Integer splashScreenId = metadata != null ? metadata.getInt(SPLASH_SCREEN_META_DATA_KEY) : null;
            return splashScreenId != null
                    ? Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP
                    ? getResources().getDrawable(splashScreenId, getTheme())
                    : getResources().getDrawable(splashScreenId)
                    : null;
        } catch (PackageManager.NameNotFoundException e) {
            // This is never expected to happen.
            return null;
        }
    }
}
结尾

本篇文章仅介绍了flutter_boost的基础使用。更加详细的demo 代码请到github上下载。希望对读者flutter学习过程有所帮助。

Android与Flutter混合开发之flutter_boost