How to use Android Fragment in Flutter plugin?

1,564

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.

Share:
1,564
piczaj
Author by

piczaj

University of Technology in Rzeszow.

Updated on December 16, 2022

Comments

  • piczaj
    piczaj over 1 year

    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 ?