Flutter

Android & Flutter 相互跳转

2021-06-09  本文已影响0人  XQSY

写在前面

本文中native和flutter的跳转是借助于咸鱼的FlutterBoost和ARouter框架实现的。

一、flutterBoost的接入

dependencies:
  flutter:
    sdk: flutter
 //配置fluterBoost
  flutter_boost:
    git:
      url: 'https://github.com/alibaba/flutter_boost.git'
      ref: '7a6ee43a65b09e62e28e19bade8d941af164dd42'
    implementation 'com.alibaba:arouter-api:1.4.1'
    implementation project(':flutter_boost')

Sync Now...

二、flutterBoost初始化

flutterBoost中需要给每个页面定义一个router_path,然后根据router_path找到对应页面再跳转。

void main() {
  WidgetsFlutterBinding.ensureInitialized();//在flutter 1.12版本中要加上此行代码
  registerFlutterBoost();//注册路由
  runApp(MyApp());
}

 ///注册页面route的方法  flutter/demo/onePage是MyOnePage页面对应的router_path
void registerFlutterBoost() { 
//所有的跳转页面都要在这里注册
  FlutterBoost.singleton.registerPageBuilders({
    “flutter/demo/onePage”: (pageName, params, _) {
           return MyOnePage(params);
    },
  });
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme:
            ThemeData(brightness: Brightness.light, primaryColor: Colors.white),
        title: 'Flutter example',
        builder: FlutterBoost.init(postPush: _onRoutePushed),// 初始化flutterBoost
        home: Container());
  }

  void _onRoutePushed(
      String pageName, String uniqueId, Map params, Route route, Future _) {}
}

 <!--flutter_boost中的activity,目前flutter跳转需要使用-->
        <activity
            android:name="com.idlefish.flutterboost.containers.BoostFlutterActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
            android:hardwareAccelerated="true"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat"
            android:windowSoftInputMode="adjustResize">
            <meta-data
                android:name="io.flutter.embedding.android.SplashScreenDrawable"
                android:resource="@android:color/transparent" />

        </activity>

在Application的onCreate中初始化

//MyApplication.java
 @Override
    public void onCreate() {
        super.onCreate();
        initFlutterboost(this);
    }

 public void initFlutterboost(Application application) {
        INativeRouter router = (context, url, urlParams, requestCode, exts) -> {
            //根据项目实现跳转的代码
            RouterService.getInstance().jumpFlutter(context, url, urlParams, requestCode, exts);
        };

        FlutterBoost.BoostLifecycleListener listener = new FlutterBoost.BoostLifecycleListener() {
            @Override
            public void beforeCreateEngine() {

            }

            @Override
            public void onEngineCreated() {
            }

            @Override
            public void onPluginsRegistered() {

            }

            @Override
            public void onEngineDestroy() {

            }
        };

        Platform platform = new FlutterBoost
                .ConfigBuilder(application, router)
                .isDebug(true)
                .whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
                .renderMode(FlutterView.RenderMode.surface)
                .lifecycleListener(listener)
                .build();

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


RouterService.java
public void jumpFlutter(Context context, String url, Map params, int requestCode, Map exts) {
        try {
            if (url.startsWith("flutter")) {//跳转flutter页面
                Intent intent = BoostFlutterActivity.withNewEngine().url(url).params(params)
                        .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context);
                if (context instanceof Activity) {
                    ((Activity) context).startActivityForResult(intent, requestCode);
                } else {
                    context.startActivity(intent);
                }
                return;
            } else {//跳转native页面
                jumpNative(context, url, params, requestCode);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

三、跳转示例代码

android jump to flutter

findViewById(R.id.tv_open_flutter).setOnClickListener(view -> {
            Map map = new HashMap();
            map.put("name", "张三");
            RouterService.getInstance().jumpFlutter(MainActivity.this, "flutter/demo/onePage", map, 10, null);
        });

flutter jump to android

//打开native页面
Future<Map<dynamic, dynamic>> openPage(String url,
      {Map<String, dynamic> pageParams, Map<String, dynamic> exts}) {
    return FlutterBoost.singleton.open(url, exts: exts, urlParams: pageParams);
  }

//关闭页面
Future<bool> closePage(BuildContext context,
      {Map<String, dynamic> result, Map<String, dynamic> exts}) {
    BoostContainerSettings settings = BoostContainer.of(context).settings;
    return FlutterBoost.singleton
        .close(settings.uniqueId, result: result, exts: exts);
  }
上一篇下一篇

猜你喜欢

热点阅读