Flutter Android混合开发-添加Flutter Fragment

萧献
2023-12-01

使用新引擎创建 FlutterFragment

使用新引擎指定路由创建 FlutterFragment

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn1" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn2" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

添加FlutterFragment:

public class MyFragmentActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG_FLUTTER_FRAGMENT = "flutter_fragment";
    private FragmentManager fragmentManager;
    private FlutterFragment flutterFragmentMain;//无指定路由
    private FlutterFragment flutterFragmentLogin;//指定路由

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_fragment);
        findViewById(R.id.btn11).setOnClickListener(this);
        findViewById(R.id.btn22).setOnClickListener(this);

        fragmentManager = getSupportFragmentManager();
        flutterFragmentMain = (FlutterFragment) fragmentManager.findFragmentByTag(TAG_FLUTTER_FRAGMENT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn11:
                if (flutterFragmentMain == null) {
                    flutterFragmentMain = FlutterFragment.createDefault();//默认构建方式
                    fragmentManager.beginTransaction()
                            .add(R.id.fragment_container, flutterFragmentMain, TAG_FLUTTER_FRAGMENT)
                            .commit();
                } else {
                    fragmentManager.beginTransaction()
                            .replace(R.id.fragment_container, flutterFragmentMain)
                            .commit();
                }
                break;
            case R.id.btn22:
                if (flutterFragmentLogin == null) {
                    flutterFragmentLogin = FlutterFragment
                            .withNewEngine()
                            .initialRoute("login")
                            .build();//指定路由构建方式
                    fragmentManager.beginTransaction()
                            .add(R.id.fragment_container, flutterFragmentLogin, TAG_FLUTTER_FRAGMENT)
                            .commit();
                } else {
                    fragmentManager.beginTransaction()
                            .replace(R.id.fragment_container, flutterFragmentLogin)
                            .commit();
                }
                break;
        }
    }
}

加载了 UI,但并不能进行一些交互和行为,通常情况下,需要将 Activity 的生命周期透传给 FlutterFragment:

    @Override
    protected void onPause() {
        super.onPause();
        flutterFragment.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        flutterFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        flutterFragment.onUserLeaveHint();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        flutterFragment.onTrimMemory(level);
    }
    ......



使用FlutterEngine创建 FlutterFragment

FlutterFragment创建方式区别,其他都一样:

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn33:
                if (flutterFragmentOldPassword == null) {
                    flutterFragmentOldPassword = FlutterFragment
                            .withCachedEngine("my_engine_id")
                            .build();//使用FlutterEngine缓存引擎
                    fragmentManager.beginTransaction()
                            .add(R.id.fragment_container, flutterFragmentOldPassword, TAG_FLUTTER_FRAGMENT)
                            .commit();
                } else {
                    fragmentManager.beginTransaction()
                            .replace(R.id.fragment_container, flutterFragmentOldPassword)
                            .commit();
                }
                break;
        }
    }



使用FlutterEngine指定路由创建 FlutterFragment

和activity一致



从指定的入口点运行Flutter

FlutterFragment支持指定的Dart入口点的规范,以针对给定的Flutter体验执行。要指定入口点,先构建build FlutterFragment:

	@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn44:
                if (flutterFragmentCodePassword == null) {
                    flutterFragmentCodePassword = FlutterFragment.withNewEngine()
                            .dartEntrypoint("mySpecialEntrypoint")
                            .build();
                    fragmentManager.beginTransaction()
                            .add(R.id.fragment_container, flutterFragmentCodePassword, TAG_FLUTTER_FRAGMENT)
                            .commit();
                } else {
                    fragmentManager.beginTransaction()
                            .replace(R.id.fragment_container, flutterFragmentCodePassword)
                            .commit();
                }
                break;
        }
    }

main.dart添加改入口方法:

import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_module/user_login_page.dart';
import 'package:flutter_module/user_update_password_page_for_code.dart';
import 'package:flutter_module/user_update_password_page_for_old.dart';

void main() => runApp(MyApp());

void mySpecialEntrypoint() => runApp(MyApps());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: <String, WidgetBuilder>{
        "login": (context) => UserLoginPage(),
        "old_password": (context) => UserUpdatePasswordForOldPage(),
        "code_password": (context) => UserUpdatePasswordForCodePage(),
        "login": (context) => UserLoginPage(),
      },
      // home: MyHomePage(title: "Flutter Demo"),
      home: _widgetForRoute(window.defaultRouteName),

    );
  }
}

class MyApps extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: <String, WidgetBuilder>{
        "login": (context) => UserLoginPage(),
        "old_password": (context) => UserUpdatePasswordForOldPage(),
        "code_password": (context) => UserUpdatePasswordForCodePage(),
        "login": (context) => UserLoginPage(),
      },
      // home: MyHomePage(title: "Flutter Demo"),
      home: _widgetForRoute('code_password'),

    );
  }
}

Widget _widgetForRoute(String route) {
  switch (route) {
    case 'login':
      return Center(
        child: UserLoginPage(),
      );
    case 'old_password':
      return  Center(
        child: UserUpdatePasswordForOldPage(),
      );
    case 'code_password':
      return Center(
        child: UserUpdatePasswordForCodePage(),
      );
    default:
      return Center(
        child: MyHomePage(title: "123456"),
      );
  }
}
 类似资料: