public class FlutterFragment
extends androidx.fragment.app.Fragment
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:
onPostResume()
onBackPressed()
onRequestPermissionsResult(int, String[], int[])
()}
onNewIntent(Intent)
()}
onUserLeaveHint()
onTrimMemory(int)
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:
FlutterFragment
is in the first Activity
displayed by the app, because
pre-warming a FlutterEngine
would have no impact in this situation.
The following illustrates how to pre-warm and cache a FlutterEngine
:
// Create and pre-warm a FlutterEngine.
FlutterEngine flutterEngine = new FlutterEngine(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
.
Modifier and Type | Class and Description |
---|---|
static class |
FlutterFragment.CachedEngineFragmentBuilder
Builder that creates a new
FlutterFragment that uses a cached FlutterEngine
with arguments that correspond to the values set on this Builder . |
static class |
FlutterFragment.NewEngineFragmentBuilder
Builder that creates a new
FlutterFragment with arguments that correspond to
the values set on this NewEngineFragmentBuilder . |
Modifier and Type | Field and Description |
---|---|
protected static String |
ARG_APP_BUNDLE_PATH
Path to Flutter's Dart code.
|
protected static String |
ARG_CACHED_ENGINE_ID
The ID of a
FlutterEngine cached in FlutterEngineCache that will be used within
the created FlutterFragment . |
protected static String |
ARG_DART_ENTRYPOINT
The Dart entrypoint method name that is executed upon initialization.
|
protected static 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 . |
protected static 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.
|
protected static String |
ARG_FLUTTER_INITIALIZATION_ARGS
Flutter shell arguments.
|
protected static String |
ARG_FLUTTERVIEW_RENDER_MODE
|
protected static String |
ARG_FLUTTERVIEW_TRANSPARENCY_MODE
|
protected static String |
ARG_HANDLE_DEEPLINKING
Whether the activity delegate should handle the deeplinking request.
|
protected static String |
ARG_INITIAL_ROUTE
Initial Flutter route that is rendered in a Navigator widget.
|
protected static String |
ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY
|
Constructor and Description |
---|
FlutterFragment() |
Modifier and Type | Method and Description |
---|---|
void |
cleanUpFlutterEngine(FlutterEngine flutterEngine)
Hook for the host to cleanup references that were established in
configureFlutterEngine(FlutterEngine) before the host is destroyed or detached. |
void |
configureFlutterEngine(FlutterEngine flutterEngine)
Configures a
FlutterEngine after its creation. |
static FlutterFragment |
createDefault()
Creates a
FlutterFragment with a default configuration. |
void |
detachFromFlutterEngine()
Callback called when the
FlutterEngine has been attached to by another activity
before this activity was destroyed. |
Activity |
getActivity()
|
String |
getAppBundlePath()
A custom path to the bundle that contains this Flutter app's resources, e.g., Dart code
snapshots.
|
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 . |
Context |
getContext()
|
String |
getDartEntrypointFunctionName()
Returns the name of the Dart method that this
FlutterFragment should execute to start a
Flutter app. |
FlutterEngine |
getFlutterEngine()
Hook for subclasses to obtain a reference to the
FlutterEngine that is owned by this
FlutterActivity . |
FlutterShellArgs |
getFlutterShellArgs()
FlutterActivityAndFragmentDelegate.Host method that is used by FlutterActivityAndFragmentDelegate to obtain Flutter shell arguments when initializing
Flutter. |
String |
getInitialRoute()
Returns the initial route that should be rendered within Flutter, once the Flutter app starts.
|
androidx.lifecycle.Lifecycle |
getLifecycle()
|
RenderMode |
getRenderMode()
|
TransparencyMode |
getTransparencyMode()
|
void |
onActivityResult(int requestCode,
int resultCode,
Intent data)
A result has been returned after an invocation of
Fragment.startActivityForResult(Intent, int) . |
void |
onAttach(Context context) |
void |
onBackPressed()
The hardware back button was pressed.
|
void |
onCreate(Bundle savedInstanceState) |
View |
onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) |
void |
onDestroyView() |
void |
onDetach() |
void |
onFlutterSurfaceViewCreated(FlutterSurfaceView flutterSurfaceView)
Invoked by this delegate when the
FlutterSurfaceView that renders the Flutter UI is
initially instantiated. |
void |
onFlutterTextureViewCreated(FlutterTextureView flutterTextureView)
Invoked by this delegate when the
FlutterTextureView that renders the Flutter UI is
initially instantiated. |
void |
onFlutterUiDisplayed()
Invoked after the
FlutterView within this FlutterFragment starts rendering
pixels to the screen. |
void |
onFlutterUiNoLongerDisplayed()
Invoked after the
FlutterView within this FlutterFragment stops rendering
pixels to the screen. |
void |
onLowMemory()
Callback invoked when memory is low.
|
void |
onNewIntent(Intent intent)
A new Intent was received by the
Activity that currently owns this Fragment . |
void |
onPause() |
void |
onPostResume() |
void |
onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults)
The result of a permission request has been received.
|
void |
onResume() |
void |
onSaveInstanceState(Bundle outState) |
void |
onStart() |
void |
onStop() |
void |
onTrimMemory(int level)
Callback invoked when memory is low.
|
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. |
boolean |
popSystemNavigator()
Allow implementer to customize the behavior needed when the Flutter framework calls to pop
the Android-side navigation stack.
|
FlutterEngine |
provideFlutterEngine(Context context)
Hook for subclasses to return a
FlutterEngine with whatever configuration is desired. |
PlatformPlugin |
providePlatformPlugin(Activity activity,
FlutterEngine flutterEngine)
Hook for the host to create/provide a
PlatformPlugin if the associated Flutter
experience should control system chrome. |
SplashScreen |
provideSplashScreen()
Provides a
SplashScreen to display while Flutter initializes and renders its first
frame. |
boolean |
shouldAttachEngineToActivity()
|
boolean |
shouldDestroyEngineWithHost()
Returns false if the
FlutterEngine within this FlutterFragment should outlive
the FlutterFragment , itself. |
boolean |
shouldHandleDeeplinking()
Whether to handle the deeplinking from the
Intent automatically if the getInitialRoute returns null. |
boolean |
shouldRestoreAndSaveState()
Whether state restoration is enabled.
|
static FlutterFragment.CachedEngineFragmentBuilder |
withCachedEngine(String engineId)
Returns a
FlutterFragment.CachedEngineFragmentBuilder to create a FlutterFragment with a cached
FlutterEngine in FlutterEngineCache . |
static FlutterFragment.NewEngineFragmentBuilder |
withNewEngine()
Returns a
FlutterFragment.NewEngineFragmentBuilder to create a FlutterFragment with a new
FlutterEngine and a desired engine configuration. |
dump, equals, getActivity, getAllowEnterTransitionOverlap, getAllowReturnTransitionOverlap, getArguments, getChildFragmentManager, getContext, getEnterTransition, getExitTransition, getFragmentManager, getHost, getId, getLayoutInflater, getLayoutInflater, getLifecycle, getLoaderManager, getParentFragment, getReenterTransition, getResources, getRetainInstance, getReturnTransition, getSavedStateRegistry, getSharedElementEnterTransition, getSharedElementReturnTransition, getString, getString, getTag, getTargetFragment, getTargetRequestCode, getText, getUserVisibleHint, getView, getViewLifecycleOwner, getViewLifecycleOwnerLiveData, getViewModelStore, hashCode, hasOptionsMenu, instantiate, instantiate, isAdded, isDetached, isHidden, isInLayout, isMenuVisible, isRemoving, isResumed, isStateSaved, isVisible, onActivityCreated, onAttach, onAttachFragment, onConfigurationChanged, onContextItemSelected, onCreateAnimation, onCreateAnimator, onCreateContextMenu, onCreateOptionsMenu, onDestroy, onDestroyOptionsMenu, onGetLayoutInflater, onHiddenChanged, onInflate, onInflate, onMultiWindowModeChanged, onOptionsItemSelected, onOptionsMenuClosed, onPictureInPictureModeChanged, onPrepareOptionsMenu, onPrimaryNavigationFragmentChanged, onViewCreated, onViewStateRestored, postponeEnterTransition, postponeEnterTransition, registerForContextMenu, requestPermissions, requireActivity, requireArguments, requireContext, requireFragmentManager, requireHost, requireParentFragment, requireView, setAllowEnterTransitionOverlap, setAllowReturnTransitionOverlap, setArguments, setEnterSharedElementCallback, setEnterTransition, setExitSharedElementCallback, setExitTransition, setHasOptionsMenu, setInitialSavedState, setMenuVisibility, setReenterTransition, setRetainInstance, setReturnTransition, setSharedElementEnterTransition, setSharedElementReturnTransition, setTargetFragment, setUserVisibleHint, shouldShowRequestPermissionRationale, startActivity, startActivity, startActivityForResult, startActivityForResult, startIntentSenderForResult, startPostponedEnterTransition, toString, unregisterForContextMenu
protected static final String ARG_DART_ENTRYPOINT
protected static final String ARG_INITIAL_ROUTE
protected static final String ARG_HANDLE_DEEPLINKING
protected static final String ARG_APP_BUNDLE_PATH
protected static final String ARG_FLUTTER_INITIALIZATION_ARGS
protected static final String ARG_FLUTTERVIEW_RENDER_MODE
protected static final String ARG_FLUTTERVIEW_TRANSPARENCY_MODE
protected static final String ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY
protected static final String ARG_CACHED_ENGINE_ID
FlutterEngine
cached in FlutterEngineCache
that will be used within
the created FlutterFragment
.protected static final String ARG_DESTROY_ENGINE_WITH_FRAGMENT
FlutterEngine
in the created FlutterFragment
should be destroyed
when the FlutterFragment
is destroyed, false if the FlutterEngine
should
outlive the FlutterFragment
.protected static final String ARG_ENABLE_STATE_RESTORATION
@NonNull public static FlutterFragment createDefault()
FlutterFragment
with a default configuration.
FlutterFragment
's default configuration creates a new FlutterEngine
within
the FlutterFragment
and uses the following settings:
To use a new FlutterEngine
with different settings, use withNewEngine()
.
To use a cached FlutterEngine
instead of creating a new one, use withCachedEngine(String)
.
@NonNull public static FlutterFragment.NewEngineFragmentBuilder withNewEngine()
FlutterFragment.NewEngineFragmentBuilder
to create a FlutterFragment
with a new
FlutterEngine
and a desired engine configuration.@NonNull public static FlutterFragment.CachedEngineFragmentBuilder withCachedEngine(@NonNull String engineId)
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()
.
public void onAttach(@NonNull Context context)
onAttach
in class androidx.fragment.app.Fragment
public void onCreate(@Nullable Bundle savedInstanceState)
onCreate
in class androidx.fragment.app.Fragment
@Nullable public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
onCreateView
in class androidx.fragment.app.Fragment
public void onStart()
onStart
in class androidx.fragment.app.Fragment
public void onResume()
onResume
in class androidx.fragment.app.Fragment
public void onPostResume()
public void onPause()
onPause
in class androidx.fragment.app.Fragment
public void onStop()
onStop
in class androidx.fragment.app.Fragment
public void onDestroyView()
onDestroyView
in class androidx.fragment.app.Fragment
public void onSaveInstanceState(Bundle outState)
onSaveInstanceState
in class androidx.fragment.app.Fragment
public void detachFromFlutterEngine()
FlutterEngine
has been attached to by another activity
before this activity was destroyed.
The expected behavior is for this activity to synchronously stop using the FlutterEngine
to avoid lifecycle crosstalk with the new activity.
public void onDetach()
onDetach
in class androidx.fragment.app.Fragment
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
See Activity.onRequestPermissionsResult(int, String[], int[])
onRequestPermissionsResult
in class androidx.fragment.app.Fragment
requestCode
- identifier passed with the initial permission requestpermissions
- permissions that were requestedgrantResults
- permission grants or denialspublic void onNewIntent(@NonNull Intent intent)
Activity
that currently owns this Fragment
.
intent
- new Intentpublic void onBackPressed()
public void onActivityResult(int requestCode, int resultCode, Intent data)
Fragment.startActivityForResult(Intent, int)
.
onActivityResult
in class androidx.fragment.app.Fragment
requestCode
- request code sent with Fragment.startActivityForResult(Intent, int)
resultCode
- code representing the result of the Activity
that was launcheddata
- any corresponding return data, held within an Intent
public void onUserLeaveHint()
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.
public void onTrimMemory(int level)
This implementation forwards a memory pressure warning to the running Flutter app.
level
- levelpublic void onLowMemory()
This implementation forwards a memory pressure warning to the running Flutter app.
onLowMemory
in interface ComponentCallbacks
onLowMemory
in class androidx.fragment.app.Fragment
@NonNull public FlutterShellArgs getFlutterShellArgs()
FlutterActivityAndFragmentDelegate.Host
method that is used by FlutterActivityAndFragmentDelegate
to obtain Flutter shell arguments when initializing
Flutter.@Nullable public String getCachedEngineId()
FlutterEngine
to use within this FlutterFragment
, or null
if this FlutterFragment
does not want to use a cached
FlutterEngine
.public boolean shouldDestroyEngineWithHost()
FlutterEngine
within this FlutterFragment
should outlive
the FlutterFragment
, itself.
Defaults to true if no custom is provided
, false if a custom FlutterEngine
is provided.
@NonNull public String getDartEntrypointFunctionName()
FlutterFragment
should execute to start a
Flutter app.
Defaults to "main".
Used by this FlutterFragment
's FlutterActivityAndFragmentDelegate.Host
@NonNull public String getAppBundlePath()
When unspecified, the value is null, which defaults to the app bundle path defined in FlutterLoader#findAppBundlePath()
.
Used by this FlutterFragment
's FlutterActivityAndFragmentDelegate.Host
@Nullable public String getInitialRoute()
Defaults to null
, which signifies a route of "/" in Flutter.
Used by this FlutterFragment
's FlutterActivityAndFragmentDelegate.Host
@NonNull public RenderMode getRenderMode()
RenderMode
for the FlutterView
displayed in this FlutterFragment
.
Defaults to RenderMode.surface
.
Used by this FlutterFragment
's FlutterActivityAndFragmentDelegate.Host
@NonNull public TransparencyMode getTransparencyMode()
TransparencyMode
for the FlutterView
displayed in this
FlutterFragment
.
Defaults to TransparencyMode.transparent
.
Used by this FlutterFragment
's FlutterActivityAndFragmentDelegate.Host
@Nullable public SplashScreen provideSplashScreen()
SplashScreenProvider
SplashScreen
to display while Flutter initializes and renders its first
frame.@Nullable public FlutterEngine provideFlutterEngine(@NonNull Context context)
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
@Nullable public FlutterEngine getFlutterEngine()
FlutterEngine
that is owned by this
FlutterActivity
.@Nullable public PlatformPlugin providePlatformPlugin(@Nullable Activity activity, @NonNull FlutterEngine flutterEngine)
PlatformPlugin
if the associated Flutter
experience should control system chrome.public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine)
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
public void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine)
configureFlutterEngine(FlutterEngine)
before the host is destroyed or detached.
This method is called in onDetach()
.
public boolean shouldAttachEngineToActivity()
shouldAttachEngineToActivity()
and shouldAttachEngineToActivity()
.
Used by this FlutterFragment
's FlutterActivityAndFragmentDelegate
public boolean shouldHandleDeeplinking()
Intent
automatically if the getInitialRoute
returns null.public void onFlutterSurfaceViewCreated(@NonNull FlutterSurfaceView flutterSurfaceView)
FlutterSurfaceView
that renders the Flutter UI is
initially instantiated.
This method is only invoked if the FlutterView.RenderMode
is set to FlutterView.RenderMode.surface
. Otherwise, onFlutterTextureViewCreated(FlutterTextureView)
is invoked.
This method is invoked before the given FlutterSurfaceView
is attached to the
View
hierarchy. Implementers should not attempt to climb the View
hierarchy
or make assumptions about relationships with other View
s.
public void onFlutterTextureViewCreated(@NonNull FlutterTextureView flutterTextureView)
FlutterTextureView
that renders the Flutter UI is
initially instantiated.
This method is only invoked if the FlutterView.RenderMode
is set to FlutterView.RenderMode.texture
. Otherwise, onFlutterSurfaceViewCreated(FlutterSurfaceView)
is invoked.
This method is invoked before the given FlutterTextureView
is attached to the
View
hierarchy. Implementers should not attempt to climb the View
hierarchy
or make assumptions about relationships with other View
s.
public void onFlutterUiDisplayed()
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
public void onFlutterUiNoLongerDisplayed()
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
public boolean shouldRestoreAndSaveState()
When this returns true, the instance state provided to onRestoreInstanceState(Bundle)
will be forwarded to the framework via the RestorationChannel
and during onSaveInstanceState(Bundle)
the current framework
instance state obtained from RestorationChannel
will be stored in the provided
bundle.
This defaults to true, unless a cached engine is used.
public boolean popSystemNavigator()
PlatformPlugin.PlatformPluginDelegate
OnBackPressedDispatcher
will be executed.@NonNull public Context getContext()
@Nullable public Activity getActivity()
@NonNull public androidx.lifecycle.Lifecycle getLifecycle()