- 向 Android 应用中添加 Flutter Fragment
- Add a FlutterFragment to an Activity with a new FlutterEngine
- Using a pre-warmed FlutterEngine
- Display a splash screen
- Run Flutter with a specified initial route
- Run Flutter from a specified entrypoint
- Control FlutterFragment’s render mode
- Display a FlutterFragment with transparency
- The relationship beween FlutterFragment and its Activity
向 Android 应用中添加 Flutter Fragment
This guide describes how to add a Flutter Fragment
to an existing Android app.In Android, a Fragment
represents a modular piece of a larger UI. AFragment
might be used to present a sliding drawer, tabbed content, a page ina ViewPager
, or it might simply represent a normal screen in asingle-Activity
app. Flutter provides a FlutterFragment
so that developerscan present a Flutter experience any place that they can use a regularFragment
.
If an Activity
is equally applicable for your application needs, considerusing a FlutterActivity
instead of a FlutterFragment
, which is quicker andeasier to use.
FlutterFragment
allows developers to control the following details of theFlutter experience within the Fragment
:
- Initial Flutter route.
- Dart entrypoint to execute.
- Opaque vs translucent background.
- Whether
FlutterFragment
should control its surroundingActivity
. - Whether a new
FlutterEngine
or a cachedFlutterEngine
should be used.
FlutterFragment
also comes with a number of calls that must be forwarded fromits surrounding Activity
. These calls allow Flutter to react appropriately toOS events.
All varieties of FlutterFragment
, and its requirements, are described in thisguide.
Add a FlutterFragment to an Activity with a new FlutterEngine
The first thing to do to use a FlutterFragment
is to add it to a hostActivity
.
To add a FlutterFragment
to a host Activity
, instantiate andattach an instance of FlutterFragment
in onCreate()
within theActivity
, or at another time that works for your app:
MyActivity.java
- public class MyActivity extends FragmentActivity {
- // Define a tag String to represent the FlutterFragment within this
- // Activity's FragmentManager. This value can be whatever you'd like.
- private static final String TAG_FLUTTER_FRAGMENT = "flutter_fragment";
- // Declare a local variable to reference the FlutterFragment so that you
- // can forward calls to it later.
- private FlutterFragment flutterFragment;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // Inflate a layout that has a container for your FlutterFragment. For
- // this example, assume that a FrameLayout exists with an ID of
- // R.id.fragment_container.
- setContentView(R.layout.my_activity_layout);
- // Get a reference to the Activity's FragmentManager to add a new
- // FlutterFragment, or find an existing one.
- FragmentManager fragmentManager = getSupportFragmentManager();
- // Attempt to find an existing FlutterFragment, in case this is not the
- // first time that onCreate() was run.
- flutterFragment = (FlutterFragment) fragmentManager
- .findFragmentByTag(TAG_FLUTTER_FRAGMENT);
- // Create and attach a FlutterFragment if one does not exist.
- if (flutterFragment == null) {
- flutterFragment = FlutterFragment.createDefault();
- fragmentManager
- .beginTransaction()
- .add(
- R.id.fragment_container,
- flutterFragment,
- TAG_FLUTTER_FRAGMENT
- )
- .commit();
- }
- }
- }
MyActivity.kt
- class MyActivity : FragmentActivity() {
- companion object {
- // Define a tag String to represent the FlutterFragment within this
- // Activity's FragmentManager. This value can be whatever you'd like.
- private const val TAG_FLUTTER_FRAGMENT = "flutter_fragment"
- }
- // Declare a local variable to reference the FlutterFragment so that you
- // can forward calls to it later.
- private var flutterFragment: FlutterFragment? = null
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- // Inflate a layout that has a container for your FlutterFragment. For
- // this example, assume that a FrameLayout exists with an ID of
- // R.id.fragment_container.
- setContentView(R.layout.my_activity_layout)
- // Get a reference to the Activity's FragmentManager to add a new
- // FlutterFragment, or find an existing one.
- val fragmentManager: FragmentManager = supportFragmentManager
- // Attempt to find an existing FlutterFragment, in case this is not the
- // first time that onCreate() was run.
- flutterFragment = fragmentManager
- .findFragmentByTag(TAG_FLUTTER_FRAGMENT) as FlutterFragment?
- // Create and attach a FlutterFragment if one does not exist.
- if (flutterFragment == null) {
- var newFlutterFragment = FlutterFragment.createDefault()
- flutterFragment = newFlutterFragment
- fragmentManager
- .beginTransaction()
- .add(
- R.id.fragment_container,
- newFlutterFragment,
- TAG_FLUTTER_FRAGMENT
- )
- .commit()
- }
- }
- }
The previous code is sufficient to render a Flutter UI that begins with a call toyour main()
Dart entrypoint, an initial Flutter route of /
, and a newFlutterEngine
. However, this code is not sufficient to achieve all expectedFlutter behavior. Flutter depends on various OS signals that must beforwarded from your host Activity
to FlutterFragment
. These calls are shown in the following example:
MyActivity.java
- public class MyActivity extends FragmentActivity {
- @Override
- public void onPostResume() {
- super.onPostResume();
- flutterFragment.onPostResume();
- }
- @Override
- protected void onNewIntent(@NonNull Intent intent) {
- flutterFragment.onNewIntent(intent);
- }
- @Override
- public void onBackPressed() {
- flutterFragment.onBackPressed();
- }
- @Override
- public void onRequestPermissionsResult(
- int requestCode,
- @NonNull String[] permissions,
- @NonNull int[] grantResults
- ) {
- flutterFragment.onRequestPermissionsResult(
- requestCode,
- permissions,
- grantResults
- );
- }
- @Override
- public void onUserLeaveHint() {
- flutterFragment.onUserLeaveHint();
- }
- @Override
- public void onTrimMemory(int level) {
- super.onTrimMemory(level);
- flutterFragment.onTrimMemory(level);
- }
- }
MyActivity.kt
- class MyActivity : FragmentActivity() {
- override fun onPostResume() {
- super.onPostResume()
- flutterFragment!!.onPostResume()
- }
- override fun onNewIntent(@NonNull intent: Intent) {
- flutterFragment!!.onNewIntent(intent)
- }
- override fun onBackPressed() {
- flutterFragment!!.onBackPressed()
- }
- override fun onRequestPermissionsResult(
- requestCode: Int,
- permissions: Array<String?>,
- grantResults: IntArray
- ) {
- flutterFragment!!.onRequestPermissionsResult(
- requestCode,
- permissions,
- grantResults
- )
- }
- override fun onUserLeaveHint() {
- flutterFragment!!.onUserLeaveHint()
- }
- override fun onTrimMemory(level: Int) {
- super.onTrimMemory(level)
- flutterFragment!!.onTrimMemory(level)
- }
- }
With the OS signals forwarded to Flutter, your FlutterFragment
works asexpected. You have now added a FlutterFragment
to your existing Android app.
The simplest integration path uses a new FlutterEngine
, which comes with anon-trivial initialization time, leading to a blank UI until Flutter isinitialized and rendered the first time. Most of this time overhead can beavoided by using a cached, pre-warmed FlutterEngine
, which is discussed next.
Using a pre-warmed FlutterEngine
By default, a FlutterFragment
creates its own instance of a FlutterEngine
,which requires non-trivial warm-up time. This means your user sees a blankFragment
for a brief moment. You can mitigate most of this warm-up time byusing an existing, pre-warmed instance of FlutterEngine
.
To use a pre-warmed FlutterEngine
in a FlutterFragment
, instantiate aFlutterFragment
with the withCachedEngine()
factory method.
MyApplication.java
- // Somewhere in your app, before your FlutterFragment is needed, like in the
- // Application class ...
- // Instantiate a FlutterEngine.
- FlutterEngine flutterEngine = new FlutterEngine(context);
- // Start executing Dart code in the FlutterEngine.
- flutterEngine.getDartExecutor().executeDartEntrypoint(
- DartEntrypoint.createDefault()
- );
- // Cache the pre-warmed FlutterEngine to be used later by FlutterFragment.
- FlutterEngineCache
- .getInstance()
- .put("my_engine_id", flutterEngine);
MyActivity.java
- flutterFragment.withCachedEngine("my_engine_id").build();
MyApplication.kt
- // Somewhere in your app, before your FlutterFragment is needed, like in the
- // Application class ...
- // Instantiate a FlutterEngine.
- val flutterEngine = FlutterEngine(context)
- // Start executing Dart code in the FlutterEngine.
- flutterEngine.getDartExecutor().executeDartEntrypoint(
- DartEntrypoint.createDefault()
- )
- // Cache the pre-warmed FlutterEngine to be used later by FlutterFragment.
- FlutterEngineCache
- .getInstance()
- .put("my_engine_id", flutterEngine)
MyActivity.kt
- flutterFragment.withCachedEngine("my_engine_id").build()
FlutterFragment
internally knows about FlutterEngineCache
and retrieves thepre-warmed FlutterEngine
based on the ID given to withCachedEngine()
.
By providing a pre-warmed FlutterEngine
, as previously shown, your app renders thefirst Flutter frame as quickly as possible.
Display a splash screen
The initial display of Flutter content requires some wait time, even if apre-warmed FlutterEngine
is used. To help improve the user experience aroundthis brief waiting period, Flutter supports the display of a splash screen untilFlutter renders its first frame. For instructions about how to show a splash screen,see the Android splash screen guide.
Run Flutter with a specified initial route
An Android app might contain many independent Flutter experiences, running indifferent FlutterFragment
s, with different FlutterEngine
s. In thesescenarios, it’s common for each Flutter experience to begin with differentinitial routes (routes other than /
). To facilitate this, FlutterFragment
’sBuilder
allows you to specify a desired initial route, as shown:
MyActivity.java
- // With a new FlutterEngine.
- FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
- .initialRoute("myInitialRoute/")
- .build();
MyActivity.kt
- // With a new FlutterEngine.
- val flutterFragment = FlutterFragment.withNewEngine()
- .initialRoute("myInitialRoute/")
- .build()
备忘 FlutterFragment
’s initial route property has no effect when a pre-warmed FlutterEngine
is used because the pre-warmed FlutterEngine
already chose an initial route. The initial route can be chosen explicitly when pre-warming a FlutterEngine
.
Run Flutter from a specified entrypoint
Similar to varying initial routes, different FlutterFragments
may want toexecute different Dart entrypoints. In a typical Flutter app, there is only oneDart entrypoint: main()
, but you can define other entrypoints.
FlutterFragment
supports specification of the desired Dart entrypoint toexecute for the given Flutter experience. To specify an entrypoint, buildFlutterFragment
, as shown:
MyActivity.java
- FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
- .dartEntrypoint("mySpecialEntrypoint")
- .build();
MyActivity.kt
- val flutterFragment = FlutterFragment.withNewEngine()
- .dartEntrypoint("mySpecialEntrypoint")
- .build()
The FlutterFragment
configuration results in the execution of a Dartentrypoint called mySpecialEntrypoint()
. Notice that the parentheses ()
arenot included in the dartEntrypoint
String
name.
备忘 FlutterFragment
’s Dart entrypoint property has no effect when a pre-warmed FlutterEngine
is used because the pre-warmed FlutterEngine
already executed a Dart entrypoint. The Dart entrypoint can be chosen explicitly when pre-warming a FlutterEngine
.
Control FlutterFragment’s render mode
FlutterFragment
can either use a SurfaceView
to render its Flutter content,or it can use a TextureView
. The default is SurfaceView
, which issignificantly better for performance than TextureView
. However, SurfaceView
can’t be interleaved in the middle of an Android View
hierarchy. ASurfaceView
must either be the bottommost View
in the hierarchy, or thetopmost View
in the hierarchy. Additionally, on Android versions beforeAndroid N, SurfaceView
s can’t be animated becuase their layout and renderingaren’t synchronized with the rest of the View
hierarchy. If either of theseuse cases are requirements for your app, then you need to use TextureView
insteadof SurfaceView
. Select a TextureView
by building a FlutterFragment
with atexture
RenderMode
:
MyActivity.java
- // With a new FlutterEngine.
- FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
- .renderMode(FlutterView.RenderMode.texture)
- .build();
- // With a cached FlutterEngine.
- FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
- .renderMode(FlutterView.RenderMode.texture)
- .build();
MyActivity.kt
- // With a new FlutterEngine.
- val flutterFragment = FlutterFragment.withNewEngine()
- .renderMode(FlutterView.RenderMode.texture)
- .build()
- // With a cached FlutterEngine.
- val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
- .renderMode(FlutterView.RenderMode.texture)
- .build()
Using the configuration shown, the resulting FlutterFragment
renders its UI toa TextureView
.
Display a FlutterFragment with transparency
By default, FlutterFragment
renders with an opaque background, using aSurfaceView
. (See “Control FlutterFragment
’s rendermode.”) That background is black for any pixels that aren’t painted by Flutter.Rendering with an opaque background is the preferred rendering mode forperformance reasons. Flutter rendering with transparency on Android negativelyaffects performance. However, there are many designs that require transparentpixels in the Flutter experience that show through to the underlying Android UI.For this reason, Flutter supports translucency in a FlutterFragment
.
备忘 Both SurfaceView
and TextureView
support transparency. However, when a SurfaceView
is instructed to render with transparency, it positions itself at a higher z-index than all other Android View
s, which means it appears above all other View
s. This is a limitation of SurfaceView
. If it’s acceptable to render your Flutter experience on top of all other content, then FlutterFragment
’s default RenderMode
of surface
is the RenderMode
that you should use. However, if you need to display Android View
s both above and below your Flutter experience, then you must specify a RenderMode
of texture
. See “Control FlutterFragment
’s render mode” for information about controlling the RenderMode
.
To enable transparency for a FlutterFragment
, build it with the followingconfiguration:
MyActivity.java
- // Using a new FlutterEngine.
- FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
- .transparencyMode(FlutterView.TransparencyMode.transparent)
- .build();
- // Using a cached FlutterEngine.
- FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
- .transparencyMode(FlutterView.TransparencyMode.transparent)
- .build();
MyActivity.kt
- // Using a new FlutterEngine.
- val flutterFragment = FlutterFragment.withNewEngine()
- .transparencyMode(FlutterView.TransparencyMode.transparent)
- .build()
- // Using a cached FlutterEngine.
- val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
- .transparencyMode(FlutterView.TransparencyMode.transparent)
- .build()
The relationship beween FlutterFragment and its Activity
Some apps choose to use Fragment
s as entire Android screens. In these apps, itwould be reasonable for a Fragment
to control system chrome like Android’sstatus bar, navigation bar, and orientation.
In other apps, Fragment
s are used to represent only a portion of a UI. AFlutterFragment
might be used to implement the inside of a drawer, a videoplayer, or a single card. In these situations, it would be inappropriate for theFlutterFragment
to affect Android’s system chrome because there are other UIpieces within the same Window
.
FlutterFragment
comes with a concept that helps differentiate between the casewhen a FlutterFragment
should be able to control its host Activity
, and thecases when a FlutterFragment
should only affect its own behavior. To preventa FlutterFragment
from exposing its Activity
to Flutter plugins, and toprevent Flutter from controlling the Activity
’s system UI, use theshouldAttachEngineToActivity()
method in FlutterFragment
’s Builder
, asshown: 9
MyActivity.java
- // Using a new FlutterEngine.
- FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
- .shouldAttachEngineToActivity(false)
- .build();
- // Using a cached FlutterEngine.
- FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
- .shouldAttachEngineToActivity(false)
- .build();
MyActivity.kt
- // Using a new FlutterEngine.
- val flutterFragment = FlutterFragment.withNewEngine()
- .shouldAttachEngineToActivity(false)
- .build()
- // Using a cached FlutterEngine.
- val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
- .shouldAttachEngineToActivity(false)
- .build()
Passing false
to the shouldAttachEngineToActivity()
Builder
methodprevents Flutter from interacting with the surrounding Activity
. The defaultvalue is true
, which allows Flutter and Flutter plugins to interact with thesurrounding Activity
.
备忘 Some plugins may expect or require an Activity
reference. Ensure that none of your plugins require an Activity
before you disable access.