Sub topic 6
Pre-warming and caching the Flutter engine
This chapter covers why the first Flutter screen in a native app can open slowly, how to start a FlutterEngine early, and how to keep it in a cache so that every screen can reuse it. It assumes you have a Flutter module and can already launch a FlutterActivity or FlutterViewController from native code, as covered in the integration chapters.
Why the first Flutter screen is slow
A FlutterEngine is the runtime that hosts your Dart code. It holds the Dart VM isolate, the rendering setup, the platform channel plumbing, and the plugin registrations. Creating one is not free. If you create an engine only when the user taps a button, the user waits while the engine does all of this:
- Load the Flutter engine and the compiled Dart code.
- Start a Dart isolate and run the entrypoint.
- Build the first widget tree and draw the first frame.
On a mid-range phone this can take several hundred milliseconds. The user sees a blank or black screen during that time.
When you launch a FlutterActivity or FlutterViewController without giving it an engine, Flutter creates a new engine on the spot. That is the simplest path and it works, but it has the slowest first frame.
The fix is to do the expensive work earlier, while the user is looking at something else, and to keep the result for later.
Pre-warming and caching
Pre-warming means creating and running an engine before it is needed. Caching means storing that engine under a name so any part of the native app can find it again.
| Approach | Engine created | First-frame latency | Memory use | Complexity |
|---|---|---|---|---|
| No pre-warm | When the screen opens | Highest | Only while screen is open | Lowest |
| Pre-warm and cache | At app start or before the screen | Lowest | Engine stays in memory | Moderate |
| Pre-warm without a cache | Early, held in one object | Low | Engine stays in memory | Moderate, but hard to share |
A cached engine also keeps its Dart state. If the user closes the Flutter screen and opens it again, the same isolate is still running, and any state held in Dart objects is still there.
Android: FlutterEngineCache
On Android, the cache is FlutterEngineCache, a singleton that maps string IDs to engines. A common place to fill it is a custom Application class, because its onCreate runs once per process before any Activity.
import android.app.Application
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val engine = FlutterEngine(this)
engine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache.getInstance().put("main_engine", engine)
}
}Register this class in AndroidManifest.xml with android:name=".MyApplication" on the <application> element. Without that line Android never instantiates it, and the cache stays empty.
To use the engine, build the Activity intent with withCachedEngine instead of the default constructor:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugin.common.MethodChannel
// In an Activity, before or when launching the Flutter screen
val engine = FlutterEngineCache.getInstance().get("main_engine")!!
MethodChannel(engine.dartExecutor.binaryMessenger, "com.example.host/session")
.setMethodCallHandler { call, result ->
when (call.method) {
"getUserName" -> result.success("Ada")
else -> result.notImplemented()
}
}
startActivity(FlutterActivity.withCachedEngine("main_engine").build(this))Two details matter here:
- The ID string must match exactly. If it does not,
FlutterActivitythrows an exception at launch because it cannot find the engine. - The engine already ran its entrypoint in
Application.onCreate.FlutterActivitydoes not run it again, so any entrypoint or route you want must be chosen when you first execute it. The next chapters cover this.
Android destruction behavior
A FlutterActivity that was started with a cached engine does not destroy the engine when the Activity finishes. That is the point of the cache, but it means you own the engine's lifetime. If you want to release the memory, destroy the engine yourself and remove it from the cache:
val cache = FlutterEngineCache.getInstance()
cache.get("main_engine")?.destroy()
cache.remove("main_engine")Use the same pattern if you ever need to rebuild the engine, for example after the user signs out and you want to drop all Dart state.
iOS: an engine you own
On iOS there is no built-in global cache class. Instead, you create a FlutterEngine, call run(), and keep a reference to it somewhere with a long lifetime. Typical choices are the AppDelegate, a dependency container, or a singleton. The example below uses a small container class.
import UIKit
import Flutter
import FlutterPluginRegistrant
final class FlutterDependencies {
let engine = FlutterEngine(name: "main_engine")
init() {
engine.run()
GeneratedPluginRegistrant.register(with: engine)
}
}
final class HomeViewController: UIViewController {
var dependencies: FlutterDependencies!
@objc func showFlutter() {
let flutterVC = FlutterViewController(
engine: dependencies.engine,
nibName: nil,
bundle: nil
)
present(flutterVC, animated: true)
}
}Points to check:
engine.run()starts the default entrypoint. It must be called before the engine is used by a view controller if you want the Dart code ready.GeneratedPluginRegistrant.register(with:)connects any Flutter plugins your module uses. Skip it and plugin calls fail with a missing-plugin error.- The
FlutterEnginemust be strongly held. If the only reference is a local variable, Swift releases the engine when the function returns, and you lose all the work you did. FlutterViewController(engine:...)attaches to the engine you pass. When the controller is dismissed, the engine keeps running.
For UIKit apps, creating the FlutterDependencies object in application(_:didFinishLaunchingWithOptions:) is the simplest way to pre-warm. For SwiftUI apps, you can create it in the App struct and pass it down as an environment object.
Choosing when to pre-warm
Pre-warming at app launch is simple, but it has costs. The engine uses memory, and starting it competes with your own app's startup work.
| Strategy | When it fits | Trade-off |
|---|---|---|
| At app launch | Flutter is used on most sessions or on the home screen | Slower app start, added memory every session |
| Just before likely use | Flutter appears after a known step, such as opening a tab | Needs a good guess about where the user goes next |
| On first use with a loading state | Flutter is rarely used | The user still waits once, then it is fast |
A useful middle ground is to start the engine after your own first screen has appeared. On Android you can post it from the first Activity. On iOS you can start it from viewDidAppear of your home view controller. This way your native UI is not delayed.
Measure before deciding. Compare time from tap to first Flutter frame, and peak memory, with and without pre-warming. A cached engine typically adds tens of megabytes, and the exact figure depends on your Dart code, assets, and device.
What a cached engine keeps
Because the engine outlives each screen, state survives between screens. This helps and hurts.
- Dart objects, providers, and singletons keep their values. A user who leaves and returns finds the same data.
- The navigation stack in Dart also survives. If the user was on a deep page and you open Flutter again, they may land there, not on your home route.
- Timers, streams, and listeners keep running while no screen is visible, unless you stop them.
If you want a clean slate on each open, tell Dart to reset. One option is a platform channel call from the host that makes the Dart side pop to its root route or clear its state. The channels chapter covers the mechanism.
Common errors
- Engine not found on Android. The ID passed to
withCachedEnginedoes not match the one used input, orMyApplicationis not registered in the manifest. - Blank screen after returning. On Android, a destroyed engine remained in the cache. Remove it with
cache.remove(id)when you destroy it. - Plugins not working on iOS.
GeneratedPluginRegistrant.register(with:)was not called on the engine. - Engine disappears on iOS. Nothing holds a strong reference to it.
- Entrypoint ran twice. Calling
run()orexecuteDartEntrypointon an engine that is already running is an error. Start each engine once. - Channel handler missing at startup. If Dart calls a channel in
initStatebefore the host registers its handler, the call fails with a missing-implementation error. Register handlers right after you create the engine, not later at launch time.
Summary of the pattern
- Create the engine once, early enough that it is ready when needed.
- Run its Dart entrypoint once.
- Register plugins and channel handlers right away.
- Store it under an ID (Android) or in a long-lived object (iOS).
- Attach screens to that engine instead of letting them build their own.
- Destroy the engine deliberately when you no longer need it.
Exercise
A team caches a FlutterEngine in Application.onCreate on Android. Users report that after signing out and signing in as another person, the Flutter screen briefly shows the previous user's data. Why does this happen, and how would you fix it?
Show answer
The cached engine keeps its Dart isolate and all Dart state alive between screens, so objects holding the first user's data are still in memory when the second user opens Flutter. To fix it, destroy the engine on sign-out with FlutterEngineCache.getInstance().get(id)?.destroy(), remove it from the cache with remove(id), and create and cache a new engine (running the entrypoint again). A lighter option is to send a platform channel message that tells Dart to clear its state and return to its root route.
Exercise
On iOS, you write let engine = FlutterEngine(name: "main_engine"); engine.run() as local variables inside a function, then present a FlutterViewController from another method. What goes wrong, and what is the fix?
Show answer
The engine is only held by a local variable, so it is released when the function returns and the view controller has no engine to use, which causes a crash or a blank screen. Keep the engine in an object with a long lifetime, such as a dependency container, the AppDelegate, or a singleton, and pass that same engine to FlutterViewController(engine:nibName:bundle:).