Sub topic 3
How a native app hosts Flutter: engine and view
This chapter assumes you have created a Flutter module and can build a native Android or iOS app with Gradle or Xcode. You do not need to have wired the module into the host yet. The next two chapters cover that step by step. Here you build the mental model behind it: what the host actually runs, what it displays, and who owns each part.
The two halves: engine and view
A Flutter screen inside a native app is built from two separate objects.
- The engine runs your Dart code. It holds the Dart VM isolate, the rendering pipeline, the platform channel plumbing, and the threads that drive them. It has no pixels of its own.
- The view draws the engine's output on screen. It also forwards touches, keyboard input, and lifecycle events from the native UI toolkit back to the engine.
In a plain Flutter app you never see this split, because the generated runner creates both and joins them. In add-to-app, you decide when each exists, which is why you need to know the pieces.
| Concept | Android | iOS |
|---|---|---|
| Engine | `FlutterEngine` | `FlutterEngine` |
| Dart execution | `DartExecutor` (`engine.dartExecutor`) | `engine.run()` or `run(withEntrypoint:)` |
| View | `FlutterView` | `FlutterView` (internal) |
| Screen host | `FlutterActivity`, `FlutterFragment` | `FlutterViewController` |
| Message transport | `dartExecutor.binaryMessenger` | `engine.binaryMessenger` |
On both platforms the screen host is the class you use in your own code. It wraps a view and connects that view to an engine. The view class is mostly an implementation detail.
What the engine owns
Creating a FlutterEngine allocates a good deal of state. Knowing what lives inside explains the cost and the behavior later.
- A Dart isolate. Your
main()or other entrypoint runs here. Widget state, timers, and any Dart singletons live in this isolate's memory. - Task runners. The engine uses separate threads for the platform side, UI (Dart), raster (GPU work), and I/O. Your Dart code never blocks the host's main thread unless it makes a blocking native call.
- Platform channels. Messages between native code and Dart pass through the engine's binary messenger. Channel names and codecs must match on both sides.
- Plugin registrations. Plugins from
pubspec.yamlregister their native halves against a specific engine instance.
The engine does not start running Dart on construction. On Android you call dartExecutor.executeDartEntrypoint(...). On iOS you call run(). Until then, the engine is allocated but idle.
Each engine you create pays for its own isolate, threads, and memory. This is the main cost of add-to-app, and the reason engine reuse gets its own chapter.
What the view owns
The view is the bridge to native rendering and input.
On Android, FlutterView is a native View that renders into either a SurfaceView or a TextureView. The RenderMode setting chooses between them. surface is faster. texture composes better when the Flutter content must be animated, translucent, or placed in a scrolling native layout. Input events from the Android view system become Flutter pointer events, and the activity lifecycle (onResume, onPause) is relayed to Dart so that AppLifecycleState stays accurate.
On iOS, the FlutterViewController owns a FlutterView, which draws using Metal. The controller relays touches, keyboard events, orientation and size changes, and application lifecycle notifications to the engine.
In both cases the view does two jobs. It draws frames the engine produces and it forwards input the engine consumes.
Attaching and detaching
A view can show nothing until it is attached to an engine. Attachment is the central operation in add-to-app.
- An engine can be attached to only one view at a time.
- A view is attached to one engine for its lifetime.
- When a screen host is created, it attaches its view to an engine. When the host goes away, it detaches.
- Detaching does not stop the engine. The Dart isolate keeps running, with all its state, though the engine stops producing frames because there is no surface to draw on.
This last point drives most design decisions. Dart state outlives the screen if the engine does. If you keep an engine around and show it twice, the second screen appears with the Dart state from the first still in memory. If you want a fresh screen each time, either reset your state in Dart or create a new engine.
Implicit versus explicit engines
Both platforms let the screen host create its own engine, or let you supply one.
Implicit engine. You create the screen host and it builds an engine for itself. This is the least code and a good first test. The engine starts when the screen opens, so the user waits for engine startup and the first Dart frame. The engine is destroyed with the screen.
On Android:
import android.content.Context
import io.flutter.embedding.android.FlutterActivity
fun openCart(context: Context) {
context.startActivity(
FlutterActivity
.withNewEngine()
.initialRoute("/cart")
.build(context)
)
}On iOS:
import UIKit
import Flutter
final class ImplicitHostViewController: UIViewController {
@objc func showFlutter() {
let flutterVC = FlutterViewController(
project: nil,
nibName: nil,
bundle: nil
)
present(flutterVC, animated: true)
}
}Explicit engine. You create and run the engine yourself, then hand it to the screen host. The engine can be created before the user asks for the screen, so the screen appears faster. The engine can also outlive the screen. You become responsible for its lifetime.
On Android the explicit path puts the engine in FlutterEngineCache and opens the screen with FlutterActivity.withCachedEngine(...). On iOS you pass the engine to FlutterViewController(engine:nibName:bundle:), as in the spine's earlier example. The following chapters build both out in full.
Ownership rules for explicit engines
An explicit engine makes you answer four questions.
- Who creates it? Usually the
Applicationclass on Android, or an app-level dependency object on iOS. Creating it in a screen would defeat the purpose. - When does it start running Dart? Starting early speeds up the first screen but adds memory and startup work to the app launch.
- Who registers plugins and channels? Plugin registration is per engine. On iOS you call
GeneratedPluginRegistrant.register(with: engine). On Android, aFlutterEnginecreated by hand registers generated plugins automatically unless you opt out. Channel handlers are also registered per engine, using that engine's binary messenger. - When does it die? On Android, a cached engine is not destroyed when its activity is. You must call
destroy()yourself when you no longer need it. On iOS, the engine is released when its last reference goes away, so keep it in an object that lives as long as you want it to run.
A channel belongs to an engine
A common surprise is that platform channels are scoped to an engine rather than to the app. In the Dart module, MethodChannel('com.example.host/session') talks to whichever engine runs that isolate. In the host, you create the matching channel from that same engine's messenger:
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
fun registerSessionChannel(engine: FlutterEngine) {
MethodChannel(engine.dartExecutor.binaryMessenger, "com.example.host/session")
.setMethodCallHandler { call, result ->
when (call.method) {
"getUserName" -> result.success("Ada")
else -> result.notImplemented()
}
}
}If the host has two engines, each needs its own registration. A handler set on engine A never receives calls from engine B. Registering the handler before the Dart code makes its first call avoids a MissingPluginException. For a pre-warmed engine, that means registering right after you create it, before any screen is shown.
Common errors
- Blank screen on Android after returning to a cached engine. Check that you did not call
engine.destroy()while the cache still holds it. A destroyed engine in the cache will fail on reuse. MissingPluginExceptionfrom Dart. The channel name differs between sides, or the handler is registered on a different engine than the one running the Dart code.- Old state appears when you reopen a screen. The engine, and therefore the Dart isolate, was reused. Reset the state in Dart or build a fresh engine.
- Route is wrong on a reused engine. The initial route is read when the engine starts. Changing it for a running engine needs a navigation call from the host instead. Entrypoints and routes are covered in their own chapter.
- iOS screen never appears. The
FlutterViewControllerwas created with an engine that was not run, orrun()was called twice. Run the engine exactly once.
How to choose
Choose by what you can measure.
| Situation | Suggested approach |
|---|---|
| Prototype, one rarely used screen | Implicit engine |
| Flutter screen opened often or on a critical path | Explicit engine, started early and reused |
| Dart state must persist between visits | Explicit engine, kept alive |
| Every visit must start clean | Implicit engine, or reset state in Dart |
| Several Flutter screens at once | Multiple engines, with shared resources (a later chapter) |
Exercise
A host app keeps one explicit FlutterEngine alive. The user opens a Flutter screen, types a name into a Dart text field, leaves the screen, and later opens the Flutter screen again with the same engine. The text field still shows the name. Why, and what are two ways to get a blank field instead?
Show answer
Detaching the view does not stop the engine, so the Dart isolate and its widget state stay in memory, and the new view attaches to that same state. To get a blank field, either clear the state in Dart when the screen is shown again (for example, on a signal sent over a MethodChannel), or use a new engine for each visit so that a new isolate starts from the entrypoint.
Exercise
You register a MethodChannel handler on engine A. The Dart code runs in engine B, which uses the same channel name, and it calls invokeMethod. What happens and why?
Show answer
The call fails with a MissingPluginException. Channels are scoped to the engine whose binary messenger they use, so a handler on engine A never receives messages from the Dart isolate in engine B. You must register the handler on engine B too.