flutter开发android部分页面,将 Flutter 添加到现有 Android 应用 - 添加单个 Flutter 页面 - 《Flutter 1.12 官方开发文档》 - 书栈网 · B...

向 Android 应用中添加 Flutter 页面

This guide describes how to add a single Flutter screen to an existing Androidapp. A Flutter screen can be added as a normal, opaque screen, or as asee-through, translucent screen. Both options are described in this guide.

Add a normal Flutter screen

e21389f3c099b6fe538226d20f97726a.gif

Step 1: Add FlutterActivity to AndroidManifest.xml

Flutter provides FlutterActivity to display a Flutter experience within anAndroid app. Like any other Activity, FlutterActivity must beregistered in your AndroidManifest.xml. Add the following XML to yourAndroidManifestxml file under your application tag:

android:name="io.flutter.embedding.android.FlutterActivity"

android:theme="@style/LaunchTheme"

android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"

android:hardwareAccelerated="true"

android:windowSoftInputMode="adjustResize"

/>

The reference to @style/LaunchTheme can be replaced by any Android theme thatwant to apply to your FlutterActivity. The choice of theme dictates thecolors applied to Android’s system chrome, like Android’s navigation bar, and tothe background color of the FlutterActivity just before the Flutter UI renders itself for the first time.

Step 2: Launch FlutterActivity

With FlutterActivity registered in your manifest file, add code to launchFlutterActivity from whatever point in your app that you’d like. The followingexample shows FlutterActivity being launched from an OnClickListener.

ExistingActivity.javamyButton.setOnClickListener(newOnClickListener(){

@Override

publicvoidonClick(Viewv){

startActivity(

FlutterActivity.createDefaultIntent(currentActivity)

);

}

});

ExistingActivity.ktmyButton.setOnClickListener{

startActivity(

FlutterActivity.createDefaultIntent(this)

)

}

The previous example assumes that your Dart entrypoint is called main(), and yourinitial Flutter route is ‘/’. The Dart entrypoint can’t be changed using Intent,but the initial route can be changed using Intent. The following exampledemonstrates how to launch a FlutterActivity that initially renders a customroute in Flutter.

ExistingActivity.javamyButton.addOnClickListener(newOnClickListener(){

@Override

publicvoidonClick(Viewv){

startActivity(

FlutterActivity

.withNewEngine()

.initialRoute("/my_route")

.build(currentActivity)

);

}

});

ExistingActivity.ktmyButton.setOnClickListener{

startActivity(

FlutterActivity

.withNewEngine()

.initialRoute("/my_route")

.build(this)

)

}

Replace "/my_route" with your desired initial route.

The use of the withNewEngine() factory method configures a FlutterActivitythat internally create its own FlutterEngine instance. This comes with a non-trivial initialization time. The alternative approach is to instructFlutterActivity to use a pre-warmed, cached FlutterEngine, which minimizesFlutter’s initialization time. That approach is discussed next.

Step 3: (Optional) Use a cached FlutterEngine

Every FlutterActivity creates its own FlutterEngine by default. EachFlutterEngine has a non-trivial, warm-up time. This means that launching astandard FlutterActivity comes with a brief delay before your Flutterexperience becomes visible. To minimize this delay, you can warm up aFlutterEngine before arriving at your FlutterActivity, and then you can useyour pre-warmed FlutterEngine instead.

To pre-warm a FlutterEngine, find a reasonable location in your app toinstantiate a FlutterEngine. The following example arbitrarily pre-warms a FlutterEngine in the Application class:

MyApplication.javapublicclassMyApplicationextendsApplication{

@Override

publicvoidonCreate(){

super.onCreate();

// Instantiate a FlutterEngine.

flutterEngine=newFlutterEngine(this);

// Start executing Dart code to pre-warm the FlutterEngine.

flutterEngine.getDartExecutor().executeDartEntrypoint(

DartEntrypoint.createDefault()

);

// Cache the FlutterEngine to be used by FlutterActivity.

FlutterEngineCache

.getInstance()

.put("my_engine_id",flutterEngine);

}

}

MyApplication.ktclassMyApplication:Application(){

lateinitvarflutterEngine:FlutterEngine

overridefun onCreate(){

super.onCreate()

// Instantiate a FlutterEngine.

flutterEngine=FlutterEngine(this)

// Start executing Dart code to pre-warm the FlutterEngine.

flutterEngine.dartExecutor.executeDartEntrypoint(

DartExecutor.DartEntrypoint.createDefault()

)

// Cache the FlutterEngine to be used by FlutterActivity.

FlutterEngineCache

.getInstance()

.put("my_engine_id",flutterEngine)

}

}

The ID passed to the FlutterEngineCache can be whatever you want. Make surethat you pass the same ID to any FlutterActiity or FlutterFragmentthat should use the cached FlutterEngine. Using FlutterActivity with acached FlutterEngine is discussed next.

备忘 To warm up a FlutterEngine, you must execute a Dart entrypoint. Keep in mind that the moment executeDartEntrypoint() is invoked, your Dart entrypoint method begins executing. If your Dart entrypoint invokes runApp() to run a Flutter app, then your Flutter app behaves as if it were running in a window of zero size until this FlutterEngine is attached to a FlutterActivity, FlutterFragment, or FlutterView. Make sure that your app behaves appropriately between the time you warm it up and the time you display Flutter content.

With a pre-warmed, cached FlutterEngine, you now need to instruct yourFlutterActivity to use the cached FlutterEngine instead of creating anew one. To accomplish this, use FlutterActivity’s withCachedEngine()builder:

ExistingActivity.javamyButton.addOnClickListener(newOnClickListener(){

@Override

publicvoidonClick(Viewv){

startActivity(

FlutterActivity

.withCachedEngine("my_engine_id")

.build(currentActivity)

);

}

});

ExistingActivity.ktmyButton.setOnClickListener{

startActivity(

FlutterActivity

.withCachedEngine("my_engine_id")

.build(this)

)

}

When using the withCachedEngine() factory method, pass the same ID that youused when caching the desired FlutterEngine.

Now, when you launch FlutterActivity, there is significantly less delay inthe display of Flutter content.

备忘 When using a cached FlutterEngine, that FlutterEngine outlives any FlutterActivity or FlutterFragment that displays it. Keep in mind that Dart code begins executing as soon as you pre-warm the FlutterEngine, and continues executing after the destruction of your FlutterActivity/FlutterFragment. To stop executing and clear resources, obtain your FlutterEngine from the FlutterEngineCache and destroy the FlutterEngine with FlutterEngine.destroy().

备忘 Runtime performance isn’t the only reason that you might pre-warm and cache a FlutterEngine. A pre-warmed FlutterEngine executes Dart code independent from a FlutterActivity, which allows such a FlutterEngine to be used to execute arbitrary Dart code at any moment. Non-UI application logic can be executed in a FlutterEngine, like networking and data caching, and in background behavior within a Service or elsewhere. When using a FlutterEngine to execute behavior in the background, be sure to adhere to all Android restrictions on background execution.

备忘 Flutter’s debug/release builds have drastically different performance characteristics. To evaluate the performance of Flutter, use a release build.

Add a translucent Flutter screen

e21389f3c099b6fe538226d20f97726a.gif

Most full-screen Flutter experiences are opaque. However, some apps would like todeploy a Flutter screen that looks like a modal, for example, a dialog or bottom sheet. Flutter supports translucent FlutterActivitys out of the box.

To make your FlutterActivity translucent, make the following changes tothe regular process of creating and launching a FlutterActivity.

Step 1: Use a theme with translucency

Android requires a special theme property for Activitys that render with a translucent background. Create or update an Android theme with thefollowing property:

true

Then, apply the translucent theme to your FlutterActivity.

android:name="io.flutter.embedding.android.FlutterActivity"

android:theme="@style/MyTheme"

android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"

android:hardwareAccelerated="true"

android:windowSoftInputMode="adjustResize"

/>

Your FlutterActivity now supports translucency. Next, you need to launch yourFlutterActivity with explicit transparency support.

Step 2: Start FlutterActivity with transparency

To launch your FlutterActivity with a transparent background, pass theappropriate BackgroundMode to the IntentBuilder:

ExistingActivity.java// Using a new FlutterEngine.

startActivity(

FlutterActivity

.withNewEngine()

.backgroundMode(FlutterActivity.BackgroundMode.transparent)

.build(context)

);

// Using a cached FlutterEngine.

startActivity(

FlutterActivity

.withCachedEngine("my_engine_id")

.backgroundMode(FlutterActivity.BackgroundMode.transparent)

.build(context)

);

ExistingActivity.kt// Using a new FlutterEngine.

startActivity(

FlutterActivity

.withNewEngine()

.backgroundMode(FlutterActivity.BackgroundMode.transparent)

.build(this)

);

// Using a cached FlutterEngine.

startActivity(

FlutterActivity

.withCachedEngine("my_engine_id")

.backgroundMode(FlutterActivity.BackgroundMode.transparent)

.build(this)

);

You now have a FlutterActivity with a transparent background.

备忘 Make sure that your Flutter content also includes a translucent background. If your Flutter UI paints a solid background color, then it still appears as though your FlutterActivity has an opaque background.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值