How To Use Android Fragment In Flutter Plugin?
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 Activi
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 asMethodCallHandler
(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
intid=0x123456; ViewGroup.LayoutParamsvParams=newFrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); FrameLayoutcontainer=newFrameLayout(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 eithersuccess()
orerror()
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
.
Post a Comment for "How To Use Android Fragment In Flutter Plugin?"