Reputation: 414
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 ?
Upvotes: 6
Views: 5510
Reputation: 161
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();
MethodChannel.Result
with either success()
or error()
otherwise, the FlutterWidget will be blocked forever. static Future<void> showNativeFragment() async {
await _channel.invokeMethod("SHOW_NATIVE_FRAGMENT");
}
And also make sure that your FlutterWidget's application Activity extends FlutterFragmentActivity
.
Upvotes: 4