Sub topic 12
Several Flutter screens with FlutterEngineGroup
This chapter assumes you have read the chapters on engine caching and Dart entrypoints. You should know how a FlutterEngine is created, how a cached engine is reused, and how a module exposes more than one entrypoint. You should also be comfortable with MethodChannel.
The problem with one engine per screen
A single cached engine works well when the app shows one Flutter screen at a time. Many native apps do not behave that way. A host might show a Flutter-based cart in one tab and a Flutter-based recommendations strip on the home screen. Or it might push a Flutter screen on top of another Flutter screen.
An engine renders to one view at a time. If two views need Flutter content at the same time, you need two engines. You have two ways to get them:
- Create each engine independently with
FlutterEngine(context). Every engine then pays the full startup cost and keeps its own copy of shared resources. - Create the engines from a
FlutterEngineGroup. Engines in a group share resources and start faster after the first one.
Each engine, group or not, runs its own Dart isolate. Isolates do not share memory. State held in a Dart variable in one engine is invisible to the other. The group saves native resources, not Dart state.
What a FlutterEngineGroup shares
A FlutterEngineGroup is a factory that creates FlutterEngine instances which are related to each other. Engines spawned from the same group share:
- The GPU context, so the font and glyph cache and the raster setup are not duplicated.
- The Dart VM and its snapshot data, so each additional engine skips most of the VM startup work.
- Some other native resources that the engine would otherwise load again.
Each spawned engine still has its own isolate, its own DartExecutor, its own platform channels, and its own plugin registrations.
The first engine created by the group takes the usual startup cost. Later engines are spawned from an existing one in the group and are cheaper in time and memory. The Flutter documentation describes the memory saving as around 180 kB per additional engine in a simple case, compared with several megabytes for an engine created alone. Treat exact numbers as a guide and measure your own app.
Using the group on Android
Create one FlutterEngineGroup and keep it for the lifetime of the app. A good place is the Application class, or a dependency container you already own. Create it once. A group built per screen defeats its purpose.
import android.app.Application
import io.flutter.embedding.engine.FlutterEngineGroup
class MyApplication : Application() {
lateinit var engineGroup: FlutterEngineGroup
override fun onCreate() {
super.onCreate()
engineGroup = FlutterEngineGroup(this)
}
}Then ask the group for an engine. The call takes a DartEntrypoint and, optionally, an initial route. This is how each screen picks its own entrypoint.
import android.content.Context
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineGroup
import io.flutter.embedding.engine.dart.DartExecutor
fun createCartEngine(context: Context, group: FlutterEngineGroup): FlutterEngine {
val entrypoint = DartExecutor.DartEntrypoint(
FlutterInjector.instance().flutterLoader().findAppBundlePath(),
"cartMain"
)
val options = FlutterEngineGroup.Options(context)
.setDartEntrypoint(entrypoint)
return group.createAndRunEngine(options)
}createAndRunEngine creates the engine and starts the Dart entrypoint in one step. If you pass options with no entrypoint, the group runs the default main(). You can also use setInitialRoute("/cart") on the options when one entrypoint serves several routes.
The entrypoint name must match a top-level Dart function annotated with @pragma('vm:entry-point'). Without the annotation, release builds can strip the function through tree shaking, and the engine fails to find it at launch.
Attaching an engine to a screen
An engine from a group is not cached under a string ID by default. You decide who owns it. A common pattern is a small holder that creates the engine when a screen starts and destroys it when the screen finishes. With a FlutterActivity you can still use the cache if the engine needs to outlive the Activity:
import io.flutter.embedding.engine.FlutterEngineCache
val engine = createCartEngine(this, (application as MyApplication).engineGroup)
FlutterEngineCache.getInstance().put("cart_engine", engine)
startActivity(FlutterActivity.withCachedEngine("cart_engine").build(this))If the engine should die with the screen, destroy it yourself. Call engine.destroy() when you are done, and remove it from FlutterEngineCache if you added it. A leaked engine keeps its isolate and its memory.
Using the group on iOS
On iOS the equivalent class is FlutterEngineGroup, created with a name and a bundle. As on Android, create it once and keep it.
import Flutter
import FlutterPluginRegistrant
final class FlutterDependencies {
let group = FlutterEngineGroup(name: "app_group", project: nil)
func makeEngine(entrypoint: String?, route: String?) -> FlutterEngine {
let options = FlutterEngineGroupOptions()
options.entrypoint = entrypoint
options.initialRoute = route
let engine = group.makeEngine(with: options)
GeneratedPluginRegistrant.register(with: engine)
return engine
}
}On iOS, makeEngine(with:) creates and runs the engine. You still register plugins on each engine yourself, because plugin registration is per engine. Leaving out GeneratedPluginRegistrant.register(with:) is a common cause of a MissingPluginException on the second screen. Present the result with FlutterViewController(engine:nibName:bundle:), exactly as with a single engine.
Pass nil for entrypoint to run main(). On iOS the initial route is set in the options, not on the view controller.
Communication between engines
Because each engine has its own isolate, two Flutter screens cannot call each other directly. If the cart screen changes the item count and the home screen shows a badge, the change has to travel through native code.
A workable design is to make the native host the single source of truth:
- The cart engine sends
addItemover itsMethodChannelto the host. - The host updates its own state, for example a repository object.
- The host pushes
cartChangedto every engine that registered interest, by callinginvokeMethodon each engine's channel. - Each Dart side updates its UI in a handler.
On the Dart side, the receiving screen registers a handler:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const HomeApp());
class HomeApp extends StatelessWidget {
const HomeApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: CartBadge());
}
}
class CartBadge extends StatefulWidget {
const CartBadge({super.key});
@override
State<CartBadge> createState() => _CartBadgeState();
}
class _CartBadgeState extends State<CartBadge> {
static const _channel = MethodChannel('com.example.host/cart');
int _count = 0;
@override
void initState() {
super.initState();
_channel.setMethodCallHandler((call) async {
if (call.method == 'cartChanged') {
setState(() => _count = call.arguments as int);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('Items: $_count')));
}
}The same channel name works on both engines. A channel is bound to a messenger, and each engine has its own messenger, so the host must register a handler on each engine it creates. If you also use Pigeon, generate the same host API and call setUp once per engine.
Lifecycle and cost rules
Engines in a group are cheap compared with standalone engines, but they are not free. Each one holds a Dart isolate, a heap, and plugin state. Plan for these rules:
- Create engines when a screen is about to appear, or pre-warm one if you know the user will probably go there. Destroy engines you no longer need.
- Do not keep a pool of idle engines "just in case". Memory adds up.
- Keep exactly one group per app process. Engines from different groups do not share resources.
- Treat the spawned engine as the owner of its view. Attaching a second view to the same engine at once is not supported.
- Plugins that keep global native state may not expect two engines. Check the plugin documentation before relying on it from multiple screens.
| Approach | Startup of extra screens | Memory per extra engine | Shared Dart state |
|---|---|---|---|
| One cached engine | Fast, reuses the engine | None, one engine | Yes, one isolate |
| Independent engines | Slow, full startup each time | High | No |
| `FlutterEngineGroup` | Fast after the first engine | Low | No |
Choose a single cached engine when screens appear one after another and can share one navigator. Choose a group when screens must be alive at the same time, or when different screens need different entrypoints and isolated state.
Debugging several engines
flutter attach connects to one running Flutter engine. With several engines, the tool lists the available Dart VM service endpoints and asks you to pick one. Pass -d <device> to choose the device, and use the printed observatory URIs to tell the engines apart. Hot reload then affects only the isolate you attached to. If you want changes to appear in both screens, attach twice or restart the app.
Because every engine runs its own isolate, an exception in one screen does not crash the other. It can leave that screen blank. Check the logs for the engine you expect.
Common mistakes
- Creating a new
FlutterEngineGroupfor every screen. The sharing only works inside one group. - Forgetting
@pragma('vm:entry-point')on a custom entrypoint. Debug builds work and release builds fail. - Registering a
MethodChannelhandler on only the first engine. Each engine needs its own handler. - Forgetting to register plugins on iOS engines made from the group.
- Expecting Dart singletons or static fields to be shared. They are not, because isolates do not share memory.
- Never calling
destroy()on an engine, which leaks the isolate.
Exercise
Your app shows a Flutter cart tab and a Flutter recommendations strip on the same screen at the same time. A teammate proposes creating two independent engines with FlutterEngine(context). What do you suggest instead, and how should the cart tab tell the strip that an item was added?
Show answer
Create one FlutterEngineGroup for the whole app and use createAndRunEngine (Android) or makeEngine(with:) (iOS) to get one engine per view. Engines from the group share the GPU context and VM data, so the second engine starts faster and uses less memory. The two engines run separate isolates and share no Dart memory, so the cart tab must send a message such as addItem to the native host over its MethodChannel. The host updates its own state and calls invokeMethod('cartChanged', count) on the strip's engine. The strip's setMethodCallHandler then updates its UI.
Exercise
On iOS, the second Flutter screen created from a FlutterEngineGroup appears, but calls to a plugin throw MissingPluginException. What is the most likely cause and the fix?
Show answer
Plugin registration is per engine, and the group does not register plugins automatically. Call GeneratedPluginRegistrant.register(with: engine) on every engine returned by makeEngine(with:) before presenting its FlutterViewController.