问题
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 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
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 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
.
来源:https://stackoverflow.com/questions/62746709/how-to-use-android-fragment-in-flutter-plugin