How to use Android Fragment in Flutter plugin?

寵の児 提交于 2020-12-13 03:32:41

问题


I need to wrap SDK created in native code iOS/Android into Flutter. On Android side there is some functionality where my Fragment or Activity needs to extend SDK Fragment or Activity to implement custom view. My question is how I can wrap SDK Fragment or Activity in Flutter plugin and let extends this on flutter project side using my plugin ? I other words I would like to have a Widget which can extend Fragment or Activity using my plugin to have ability to show Widget ui in SDK.

Using FlutterFragment, FlutterActivity in plugin is right way ?

I mean: Flutter project (Widget) <-> Flutter plugin (FlutterFragment or FlutterActivity attached to native SDK Fragment or Activity)

If not what is a possible solution ?


回答1:


I was facing the same problem and here is my solution:

  • Implement a FlutterPlugin that supports ActivityAware, refer to this FlutterPlugin with ActivityAware on how to cache the Activity, as well as MethodCallHandler (to communicate with the FlutterWidget app).

  • Implement a MethodCall e.g. SHOW_NATIVE_FRAGMENT in which it will attach the native fragment. Note: need to dynamically add a View as a container for the fragment

         int id = 0x123456;
         ViewGroup.LayoutParams vParams = new FrameLayout.LayoutParams(
                 ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
         );
         FrameLayout container = new FrameLayout(context);
         container.setLayoutParams(vParams);
         container.setId(id);
         activity.addContentView(container, vParams);
    
  • Then attach the Fragment to the Activity

        FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager();
        fm.beginTransaction()
            .replace(id, nativeFragment)
            .commitAllowingStateLoss();
  • When you are done with the Fragment, remember to call the MethodChannel.Result with either success() or error() otherwise, the FlutterWidget will be blocked forever.
  • On the FlutterWidget side, call the MethodChannel with
        static Future<void> showNativeFragment() async {
            await _channel.invokeMethod("SHOW_NATIVE_FRAGMENT");
        }

And also make sure that your FlutterWidget's application Activity extends FlutterFragmentActivity.



来源:https://stackoverflow.com/questions/62746709/how-to-use-android-fragment-in-flutter-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!