Flutter - Is possible to import a Fragment inside a Flutter App?

1,264

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

Share:
1,264
wisetap.com
Author by

wisetap.com

Flutter and Node.js developer Graduated in Computer Science Check my website and GitHub as well :)

Updated on December 04, 2022

Comments

  • wisetap.com
    wisetap.com over 1 year

    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)