【Flutter 内嵌 android 原生 View以及相互跳转】

Flutter 内嵌 android 原生 View以及相互跳转

    • [一. 内嵌android 原生View](#一. 内嵌android 原生View)
    • [二、android 与 flutter 相互跳转](#二、android 与 flutter 相互跳转)

一. 内嵌android 原生View

  1. 在android 工程的包名下,也可在MainActivity创建 android 原生view ,继承PlatformView

    // 1.自定义textview

    public static class MyTextView implements PlatformView{

     private TextView textView ;
    
     /**
      *
      * @param context
      * @param messenger 用于消息传递
      * @param id 生成时会分配一个唯一 ID
      * @param maps Flutter 传递的初始化参数。
      */
     public MyTextView(Context context ,BinaryMessenger messenger,int id,Map<String,Object> maps) {
         textView = new TextView(context);
         textView.setText("我是来自android原生的textView");
         if (maps != null){
             String text = maps.get("text").toString();
             textView.setText(text);
         }
    
         textView.setTextColor(Color.RED);
     }
    
     // 返回要嵌入 Flutter 层次结构的Android View
     @Nullable
     @Override
     public View getView() {
         return textView;
     }
    
     //释放此View时调用,此方法调用后 View 不可用,此方法需要清除所有对象引用,否则会造成内存泄漏。
     @Override
     public void dispose() {
    
     }
    

    }

  2. 新建MyViewFactory.java注册PlatformView

java 复制代码
public class MyViewFactory extends PlatformViewFactory {
    private final BinaryMessenger messenger;

    public MyViewFactory(BinaryMessenger messenger) {
        super(StandardMessageCodec.INSTANCE);
        this.messenger = messenger;
    }

    @SuppressWarnings("unchecked")
    @Override
    public PlatformView create(Context context, int id, Object args) {
        Map<String, Object> params = (Map<String, Object>) args;
        return new MainActivity.MyTextView(context, messenger, id, params);
    }

}
  1. 创建plugin
java 复制代码
public class MyViewFlutterPlugin implements FlutterPlugin {



    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        BinaryMessenger binaryMessenger = binding.getBinaryMessenger();
        binding.getPlatformViewRegistry().registerViewFactory(
                "plugins.nightfarmer.top/myview",
                new MyViewFactory(binaryMessenger));
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {

    }
}
  1. 在MainActivy 中注册
java 复制代码
    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEngine.getPlugins().add(new MyViewFlutterPlugin());
    }
  1. 在flutter 中使用
dart 复制代码
              Container(
                width: 100,
                height: 100,
                child:  AndroidView(
                  viewType: "plugins.nightfarmer.top/myview",
                  creationParams: {'text':'Flutter传给AndroidTextView的参数'},
                  creationParamsCodec: StandardMessageCodec(),
                ),
              ),

二、android 与 flutter 相互跳转

  1. flutter 挑战到 原生Activity
java 复制代码
  var platform = MethodChannel('com.example.flutter/native_channel');

  void goToNativeActivity() {
    platform.invokeMethod('goToNative');
  }

在MainActivty 中注册通道跳转到TestActivity

java 复制代码
 private static final String CHANNEL = "com.example.flutter/native_channel";

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEngine.getPlugins().add(new MyViewFlutterPlugin());

        //注册通道
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(
                (call, result) -> {
                    // 接收来自Flutter的方法调用
                    if (call.method.equals("goToNative")) {
                        Intent intent = new Intent(MainActivity.this, TestActivity.class);
                        startActivity(intent);
                        result.success(true);
                    } else {
                        result.notImplemented();
                    }
                }
        );
    }
  1. Activity 中跳转Flutter页面
    在Manifest.xml 中注册
java 复制代码
<activity
  android:name="io.flutter.embedding.android.FlutterActivity"
  android:theme="@style/LaunchTheme"
  android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
  android:hardwareAccelerated="true"
  android:windowSoftInputMode="adjustResize"
  />

根据路由跳转到Flutter 页面

java 复制代码
        startActivity(
                   FlutterActivity
                       .withNewEngine()
                      .initialRoute("/my_route")
//        .withCachedEngine("engine_id")
                        .build(currentActivity)
       );

跳转会与 2s的黑屏情况,在MyApp中

java 复制代码
public class MyApp extends Application {

    private FlutterEngine fe ;

    @Override
    public void onCreate() {
        super.onCreate();

        // 解决原生挑战到 flutter 会有2s 黑屏 的问题
        fe = new FlutterEngine(this);
        fe.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
        FlutterEngineCache.getInstance().put("engine_id",fe);
    }

    //当application 销毁的时候调用
    @Override
    public void onTerminate() {
        //销毁flutter引擎
        fe.destroy();
        super.onTerminate();
    }
}

在清单文件中注册 MyApp

java 复制代码
 <application
        android:name="com.qxx.ai_score_manager_flutter.MyApp">
相关推荐
比格丽巴格丽抱6 小时前
flutter项目苹果编译运行打包上线
flutter·ios
长亭外的少年7 小时前
Kotlin 编译失败问题及解决方案:从守护进程到 Gradle 配置
android·开发语言·kotlin
SoaringHeart7 小时前
Flutter进阶:基于 MLKit 的 OCR 文字识别
前端·flutter
建群新人小猿9 小时前
会员等级经验问题
android·开发语言·前端·javascript·php
1024小神10 小时前
tauri2.0版本开发苹果ios和安卓android应用,环境搭建和最后编译为apk
android·ios·tauri
兰琛10 小时前
20241121 android中树结构列表(使用recyclerView实现)
android·gitee
AiFlutter11 小时前
Flutter通过 Coap发送组播
flutter
Y多了个想法11 小时前
RK3568 android11 适配敦泰触摸屏 FocalTech-ft5526
android·rk3568·触摸屏·tp·敦泰·focaltech·ft5526
NotesChapter12 小时前
Android吸顶效果,并有着ViewPager左右切换
android
_祝你今天愉快13 小时前
分析android :The binary version of its metadata is 1.8.0, expected version is 1.5.
android