12

In Flutter is possible to call Java code from Dart. Also, the plugin android_intent allows to start a Java Android Activity using Dart code

But, if we want to use an Android Fragment inside a Flutter Widget, is this possible? How can we do that?

Or the only way to use Fragments is declaring a new Activity in Java, and call to start the Activity in Flutter? (Like I said at the beginning)

4
  • So far in my research, I have only come upon calling Android activity using platform channels or android_intent package. Would calling a FragmentActivity work? Commented Jun 5, 2020 at 14:51
  • Hi, @WiseTap did you find any solution for this? Commented Mar 18, 2021 at 5:35
  • @MilanJoseph no :( Commented Mar 18, 2021 at 13:33
  • hi, @wisetap.com can you help me, please if you got a way to do this? Commented Apr 6, 2023 at 8:58

2 Answers 2

1

So far I couldn't find any way to implement directly implement, in a straight forward manner, android components inside a flutter app. However is possible the opposite things, that is using a Flutter fragment inside an android application. So I can propose you a workaround for this problem that may lead to the same result:

  1. use a method channel to start a new android activity:
void startAndroidActivity() async {
    //TODO: fix result type, etc.
    dynamic result = await MethodChannel("CHANNEL_X").invokeMethod('METHOD');
 }
public class MainActivity extends FlutterActivity {

    private MethodChannel.Result result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MethodChannel(getFlutterView(), "CHANNEL_X").setMethodCallHandler((call, result) -> {
            if (call.method.equals("METHOD")) {
                Intent intent = new Intent(this, MyActivity.class);
                this.result = result;
                startActivityForResult(intent, data);
            }
        });
        GeneratedPluginRegistrant.registerWith(this);
    }

 //TODO: Handle result

}
  1. Implement your android components and import the flutter fragment. For this topic, I leave you this reference: https://flutter.dev/docs/development/add-to-app/android/add-flutter-fragment

Another reference I can give you is this one, that maybe can allow you to import what you want in Flutter, but it requires a bit more time: https://medium.com/@KarthikPonnam/build-your-own-plugin-using-platformviews-flutter-5b42b4c4fb0a

1
  • hi @AndreaCostanzo1 I need to embed a native fragment to the Flutter app have an idea? thanks Commented Apr 6, 2023 at 8:59
0

you can use data binding method to access the fragment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.