Class FlutterFragment

java.lang.Object
androidx.fragment.app.Fragment
io.flutter.embedding.android.FlutterFragment
All Implemented Interfaces:
ComponentCallbacks, ComponentCallbacks2, View.OnCreateContextMenuListener, androidx.lifecycle.LifecycleOwner, androidx.lifecycle.ViewModelStoreOwner, androidx.savedstate.SavedStateRegistryOwner, io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.DelegateFactory, FlutterEngineConfigurator, FlutterEngineProvider, PlatformPlugin.PlatformPluginDelegate

public class FlutterFragment extends androidx.fragment.app.Fragment implements ComponentCallbacks2, io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.DelegateFactory
Fragment which displays a Flutter UI that takes up all available Fragment space.

Using a FlutterFragment requires forwarding a number of calls from an Activity to ensure that the internal Flutter app behaves as expected:

  1. onPostResume()
  2. onBackPressed()
  3. onRequestPermissionsResult(int, String[], int[])
  4. onNewIntent(Intent)
  5. onUserLeaveHint()
onBackPressed() does not need to be called through if the fragment is constructed by one of the builders with shouldAutomaticallyHandleOnBackPressed(true).

Additionally, when starting an Activity for a result from this Fragment, be sure to invoke Fragment.startActivityForResult(Intent, int) rather than Activity.startActivityForResult(Intent, int). If the Activity version of the method is invoked then this Fragment will never receive its Fragment.onActivityResult(int, int, Intent) callback.

If convenient, consider using a FlutterActivity instead of a FlutterFragment to avoid the work of forwarding calls.

FlutterFragment supports the use of an existing, cached FlutterEngine. To use a cached FlutterEngine, ensure that the FlutterEngine is stored in FlutterEngineCache and then use withCachedEngine(String) to build a FlutterFragment with the cached FlutterEngine's ID.

It is generally recommended to use a cached FlutterEngine to avoid a momentary delay when initializing a new FlutterEngine. The two exceptions to using a cached FlutterEngine are:

  • When FlutterFragment is in the first Activity displayed by the app, because pre-warming a FlutterEngine would have no impact in this situation.
  • When you are unsure when/if you will need to display a Flutter experience.

The following illustrates how to pre-warm and cache a FlutterEngine:


 // Create and pre-warm a FlutterEngine.
 FlutterEngineGroup group = new FlutterEngineGroup(context);
 FlutterEngine flutterEngine = group.createAndRunDefaultEngine(context);
 flutterEngine
   .getDartExecutor()
   .executeDartEntrypoint(DartEntrypoint.createDefault());

 // Cache the pre-warmed FlutterEngine in the FlutterEngineCache.
 FlutterEngineCache.getInstance().put("my_engine", flutterEngine);
 

If Flutter is needed in a location that can only use a View, consider using a FlutterView. Using a FlutterView requires forwarding some calls from an Activity, as well as forwarding lifecycle calls from an Activity or a Fragment.

  • Field Details

    • FLUTTER_VIEW_ID

      public static final int FLUTTER_VIEW_ID
      The ID of the FlutterView created by this activity.

      This ID can be used to lookup FlutterView in the Android view hierarchy. For more, see View.findViewById(int).

    • ARG_DART_ENTRYPOINT

      protected static final String ARG_DART_ENTRYPOINT
      The Dart entrypoint method name that is executed upon initialization.
      See Also:
    • ARG_DART_ENTRYPOINT_URI

      protected static final String ARG_DART_ENTRYPOINT_URI
      The Dart entrypoint method's URI that is executed upon initialization.
      See Also:
    • ARG_DART_ENTRYPOINT_ARGS

      protected static final String ARG_DART_ENTRYPOINT_ARGS
      The Dart entrypoint arguments that is executed upon initialization.
      See Also:
    • ARG_INITIAL_ROUTE

      protected static final String ARG_INITIAL_ROUTE
      Initial Flutter route that is rendered in a Navigator widget.
      See Also:
    • ARG_HANDLE_DEEPLINKING

      protected static final String ARG_HANDLE_DEEPLINKING
      Whether the activity delegate should handle the deeplinking request.
      See Also:
    • ARG_APP_BUNDLE_PATH

      protected static final String ARG_APP_BUNDLE_PATH
      Path to Flutter's Dart code.
      See Also:
    • ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW

      protected static final String ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW
      Whether to delay the Android drawing pass till after the Flutter UI has been displayed.
      See Also:
    • ARG_FLUTTER_INITIALIZATION_ARGS

      protected static final String ARG_FLUTTER_INITIALIZATION_ARGS
      Flutter shell arguments.
      See Also:
    • ARG_FLUTTERVIEW_RENDER_MODE

      protected static final String ARG_FLUTTERVIEW_RENDER_MODE
      RenderMode to be used for the FlutterView in this FlutterFragment
      See Also:
    • ARG_FLUTTERVIEW_TRANSPARENCY_MODE

      protected static final String ARG_FLUTTERVIEW_TRANSPARENCY_MODE
      TransparencyMode to be used for the FlutterView in this FlutterFragment
      See Also:
    • ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY

      protected static final String ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY
      See Also:
    • ARG_CACHED_ENGINE_ID

      protected static final String ARG_CACHED_ENGINE_ID
      The ID of a FlutterEngine cached in FlutterEngineCache that will be used within the created FlutterFragment.
      See Also:
    • ARG_CACHED_ENGINE_GROUP_ID

      protected static final String ARG_CACHED_ENGINE_GROUP_ID
      See Also:
    • ARG_DESTROY_ENGINE_WITH_FRAGMENT

      protected static final String ARG_DESTROY_ENGINE_WITH_FRAGMENT
      True if the FlutterEngine in the created FlutterFragment should be destroyed when the FlutterFragment is destroyed, false if the FlutterEngine should outlive the FlutterFragment.
      See Also:
    • ARG_ENABLE_STATE_RESTORATION

      protected static final String ARG_ENABLE_STATE_RESTORATION
      True if the framework state in the engine attached to this engine should be stored and restored when this fragment is created and destroyed.
      See Also:
    • ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED

      protected static final String ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED
      True if the fragment should receive onBackPressed() events automatically, without requiring an explicit activity call through.
      See Also:
  • Constructor Details

    • FlutterFragment

      public FlutterFragment()
  • Method Details

    • createDefault

      @NonNull public static FlutterFragment createDefault()
      Creates a FlutterFragment with a default configuration.

      FlutterFragment's default configuration creates a new FlutterEngine within the FlutterFragment and uses the following settings:

      • Dart entrypoint: "main"
      • Initial route: "/"
      • Render mode: surface
      • Transparency mode: transparent

      To use a new FlutterEngine with different settings, use withNewEngine().

      To use a cached FlutterEngine instead of creating a new one, use withCachedEngine(String).

    • withNewEngine

      @NonNull public static FlutterFragment.NewEngineFragmentBuilder withNewEngine()
      Returns a FlutterFragment.NewEngineFragmentBuilder to create a FlutterFragment with a new FlutterEngine and a desired engine configuration.
    • withCachedEngine

      @NonNull public static FlutterFragment.CachedEngineFragmentBuilder withCachedEngine(@NonNull String engineId)
      Returns a FlutterFragment.CachedEngineFragmentBuilder to create a FlutterFragment with a cached FlutterEngine in FlutterEngineCache.

      An IllegalStateException will be thrown during the lifecycle of the FlutterFragment if a cached FlutterEngine is requested but does not exist in the cache.

      To create a FlutterFragment that uses a new FlutterEngine, use createDefault() or withNewEngine().

    • withNewEngineInGroup

      @NonNull public static FlutterFragment.NewEngineInGroupFragmentBuilder withNewEngineInGroup(@NonNull String engineGroupId)
      Returns a FlutterFragment.NewEngineInGroupFragmentBuilder to create a FlutterFragment with a cached FlutterEngineGroup in FlutterEngineGroupCache.

      An IllegalStateException will be thrown during the lifecycle of the FlutterFragment if a cached FlutterEngineGroup is requested but does not exist in the FlutterEngineGroupCache.

    • createDelegate

      public io.flutter.embedding.android.FlutterActivityAndFragmentDelegate createDelegate(io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.Host host)
      Default delegate factory that creates a simple FlutterActivityAndFragmentDelegate instance.
      Specified by:
      createDelegate in interface io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.DelegateFactory
    • getExclusiveAppComponent

      public ExclusiveAppComponent<Activity> getExclusiveAppComponent()
      Returns the Android App Component exclusively attached to FlutterEngine.
    • onAttach

      public void onAttach(@NonNull Context context)
      Overrides:
      onAttach in class androidx.fragment.app.Fragment
    • onCreate

      public void onCreate(@Nullable Bundle savedInstanceState)
      Overrides:
      onCreate in class androidx.fragment.app.Fragment
    • onCreateView

      @Nullable public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
      Overrides:
      onCreateView in class androidx.fragment.app.Fragment
    • onStart

      public void onStart()
      Overrides:
      onStart in class androidx.fragment.app.Fragment
    • onResume

      public void onResume()
      Overrides:
      onResume in class androidx.fragment.app.Fragment
    • onPostResume

      public void onPostResume()
    • onPause

      public void onPause()
      Overrides:
      onPause in class androidx.fragment.app.Fragment
    • onStop

      public void onStop()
      Overrides:
      onStop in class androidx.fragment.app.Fragment
    • onViewCreated

      public void onViewCreated(View view, Bundle savedInstanceState)
      Overrides:
      onViewCreated in class androidx.fragment.app.Fragment
    • onDestroyView

      public void onDestroyView()
      Overrides:
      onDestroyView in class androidx.fragment.app.Fragment
    • onSaveInstanceState

      public void onSaveInstanceState(Bundle outState)
      Overrides:
      onSaveInstanceState in class androidx.fragment.app.Fragment
    • detachFromFlutterEngine

      public void detachFromFlutterEngine()
    • onDetach

      public void onDetach()
      Overrides:
      onDetach in class androidx.fragment.app.Fragment
    • onRequestPermissionsResult

      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
      The result of a permission request has been received.

      See Activity.onRequestPermissionsResult(int, String[], int[])

      Overrides:
      onRequestPermissionsResult in class androidx.fragment.app.Fragment
      Parameters:
      requestCode - identifier passed with the initial permission request
      permissions - permissions that were requested
      grantResults - permission grants or denials
    • onNewIntent

      public void onNewIntent(@NonNull Intent intent)
      A new Intent was received by the Activity that currently owns this Fragment.

      See Activity.onNewIntent(Intent)

      Parameters:
      intent - new Intent
    • onBackPressed

      public void onBackPressed()
      The hardware back button was pressed.

      If the fragment uses shouldAutomaticallyHandleOnBackPressed(true), this method should not be called through. It will be called automatically instead.

      See Activity.onBackPressed()

    • onActivityResult

      public void onActivityResult(int requestCode, int resultCode, Intent data)
      A result has been returned after an invocation of Fragment.startActivityForResult(Intent, int).

      Overrides:
      onActivityResult in class androidx.fragment.app.Fragment
      Parameters:
      requestCode - request code sent with Fragment.startActivityForResult(Intent, int)
      resultCode - code representing the result of the Activity that was launched
      data - any corresponding return data, held within an Intent
    • onUserLeaveHint

      public void onUserLeaveHint()
      The Activity that owns this Fragment is about to go to the background as the result of a user's choice/action, i.e., not as the result of an OS decision.

      See Activity.onUserLeaveHint()

    • onTrimMemory

      public void onTrimMemory(int level)
      Callback invoked when memory is low.

      This implementation forwards a memory pressure warning to the running Flutter app.

      Specified by:
      onTrimMemory in interface ComponentCallbacks2
      Parameters:
      level - level
    • getFlutterShellArgs

      @NonNull public FlutterShellArgs getFlutterShellArgs()
      FlutterActivityAndFragmentDelegate.Host method that is used by FlutterActivityAndFragmentDelegate to obtain Flutter shell arguments when initializing Flutter.
    • getCachedEngineId

      @Nullable public String getCachedEngineId()
      Returns the ID of a statically cached FlutterEngine to use within this FlutterFragment, or null if this FlutterFragment does not want to use a cached FlutterEngine.
    • getCachedEngineGroupId

      @Nullable public String getCachedEngineGroupId()
      Returns the ID of a statically cached FlutterEngineGroup to use within this FlutterFragment, or null if this FlutterFragment does not want to use a cached FlutterEngineGroup.
    • shouldDestroyEngineWithHost

      public boolean shouldDestroyEngineWithHost()
      Returns false if the FlutterEngine within this FlutterFragment should outlive the FlutterFragment, itself.

      Defaults to true if no custom is provided, false if a custom FlutterEngine is provided.

    • getDartEntrypointFunctionName

      @NonNull public String getDartEntrypointFunctionName()
      Returns the name of the Dart method that this FlutterFragment should execute to start a Flutter app.

      Defaults to "main".

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • getDartEntrypointArgs

      @Nullable public List<String> getDartEntrypointArgs()
      The Dart entrypoint arguments will be passed as a list of string to Dart's entrypoint function.

      A value of null means do not pass any arguments to Dart's entrypoint function.

      Subclasses may override this method to directly control the Dart entrypoint arguments.

    • getDartEntrypointLibraryUri

      @Nullable public String getDartEntrypointLibraryUri()
      Returns the library URI of the Dart method that this FlutterFragment should execute to start a Flutter app.

      Defaults to null (example value: "package:foo/bar.dart").

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • getAppBundlePath

      @NonNull public String getAppBundlePath()
      A custom path to the bundle that contains this Flutter app's resources, e.g., Dart code snapshots.

      When unspecified, the value is null, which defaults to the app bundle path defined in FlutterLoader.findAppBundlePath().

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • getInitialRoute

      @Nullable public String getInitialRoute()
      Returns the initial route that should be rendered within Flutter, once the Flutter app starts.

      Defaults to null, which signifies a route of "/" in Flutter.

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • getRenderMode

      @NonNull public RenderMode getRenderMode()
      Returns the desired RenderMode for the FlutterView displayed in this FlutterFragment.

      Defaults to RenderMode.surface.

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • getTransparencyMode

      @NonNull public TransparencyMode getTransparencyMode()
      Returns the desired TransparencyMode for the FlutterView displayed in this FlutterFragment.

      Defaults to TransparencyMode.transparent.

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • provideFlutterEngine

      @Nullable public FlutterEngine provideFlutterEngine(@NonNull Context context)
      Hook for subclasses to return a FlutterEngine with whatever configuration is desired.

      By default this method defers to this FlutterFragment's surrounding Activity, if that Activity implements FlutterEngineProvider. If this method is overridden, the surrounding Activity will no longer be given an opportunity to provide a FlutterEngine, unless the subclass explicitly implements that behavior.

      Consider returning a cached FlutterEngine instance from this method to avoid the typical warm-up time that a new FlutterEngine instance requires.

      If null is returned then a new default FlutterEngine will be created to back this FlutterFragment.

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

      Specified by:
      provideFlutterEngine in interface FlutterEngineProvider
      Parameters:
      context - The current context. e.g. An activity.
      Returns:
      The Flutter engine.
    • getFlutterEngine

      @Nullable public FlutterEngine getFlutterEngine()
      Hook for subclasses to obtain a reference to the FlutterEngine that is owned by this FlutterActivity.
    • providePlatformPlugin

      @Nullable public PlatformPlugin providePlatformPlugin(@Nullable Activity activity, @NonNull FlutterEngine flutterEngine)
    • configureFlutterEngine

      public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine)
      Configures a FlutterEngine after its creation.

      This method is called after provideFlutterEngine(Context), and after the given FlutterEngine has been attached to the owning FragmentActivity. See ActivityControlSurface.attachToActivity(ExclusiveAppComponent, Lifecycle).

      It is possible that the owning FragmentActivity opted not to connect itself as an ActivityControlSurface. In that case, any configuration, e.g., plugins, must not expect or depend upon an available Activity at the time that this method is invoked.

      The default behavior of this method is to defer to the owning FragmentActivity as a FlutterEngineConfigurator. Subclasses can override this method if the subclass needs to override the FragmentActivity's behavior, or add to it.

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

      Specified by:
      configureFlutterEngine in interface FlutterEngineConfigurator
      Parameters:
      flutterEngine - The Flutter engine.
    • cleanUpFlutterEngine

      public void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine)
      Hook for the host to cleanup references that were established in configureFlutterEngine(FlutterEngine) before the host is destroyed or detached.

      This method is called in onDetach().

      Specified by:
      cleanUpFlutterEngine in interface FlutterEngineConfigurator
      Parameters:
      flutterEngine - The Flutter engine.
    • shouldAttachEngineToActivity

      public boolean shouldAttachEngineToActivity()
      See shouldAttachEngineToActivity() and shouldAttachEngineToActivity().

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate

    • shouldHandleDeeplinking

      public boolean shouldHandleDeeplinking()
      Whether to handle the deeplinking from the Intent automatically if the getInitialRoute returns null.
    • onFlutterSurfaceViewCreated

      public void onFlutterSurfaceViewCreated(@NonNull FlutterSurfaceView flutterSurfaceView)
    • onFlutterTextureViewCreated

      public void onFlutterTextureViewCreated(@NonNull FlutterTextureView flutterTextureView)
    • onFlutterUiDisplayed

      public void onFlutterUiDisplayed()
      Invoked after the FlutterView within this FlutterFragment starts rendering pixels to the screen.

      This method forwards onFlutterUiDisplayed() to its attached Activity, if the attached Activity implements FlutterUiDisplayListener.

      Subclasses that override this method must call through to the super method.

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • onFlutterUiNoLongerDisplayed

      public void onFlutterUiNoLongerDisplayed()
      Invoked after the FlutterView within this FlutterFragment stops rendering pixels to the screen.

      This method forwards onFlutterUiNoLongerDisplayed() to its attached Activity, if the attached Activity implements FlutterUiDisplayListener.

      Subclasses that override this method must call through to the super method.

      Used by this FlutterFragment's FlutterActivityAndFragmentDelegate.Host

    • shouldRestoreAndSaveState

      public boolean shouldRestoreAndSaveState()
    • updateSystemUiOverlays

      public void updateSystemUiOverlays()
    • shouldDispatchAppLifecycleState

      public boolean shouldDispatchAppLifecycleState()
      Give the host application a chance to take control of the app lifecycle events.

      Return false means the host application dispatches these app lifecycle events, while return true means the engine dispatches these events.

      Defaults to true.

    • attachToEngineAutomatically

      public boolean attachToEngineAutomatically()
      Whether to automatically attach the FlutterView to the engine.

      Returning false means that the task of attaching the FlutterView to the engine will be taken over by the host application.

      Defaults to true.

    • popSystemNavigator

      public boolean popSystemNavigator()
      Allow implementer to customize the behavior needed when the Flutter framework calls to pop the Android-side navigation stack.

      Avoid overriding this method when using shouldAutomaticallyHandleOnBackPressed(true). If you do, you must always return super.popSystemNavigator() rather than return false. Otherwise the navigation behavior will recurse infinitely between this method and onBackPressed(), breaking navigation.

      Specified by:
      popSystemNavigator in interface PlatformPlugin.PlatformPluginDelegate
      Returns:
      true if the implementation consumed the pop signal. If false, a default behavior of finishing the activity or sending the signal to OnBackPressedDispatcher will be executed.
    • getContext

      @NonNull Context getContext()
      Returns the Context that backs the host Activity or Fragment.
    • getActivity

      @Nullable Activity getActivity()
      Returns the host Activity or the Activity that is currently attached to the host Fragment.
    • getLifecycle

      @NonNull androidx.lifecycle.Lifecycle getLifecycle()
      Returns the Lifecycle that backs the host Activity or Fragment.