Sub topic 8
Choosing a Dart entrypoint and initial route
A Flutter module can show many different screens, and the native host decides which one appears first. It does this with two settings, a Dart entrypoint and an initial route. This chapter explains what each setting does and when it takes effect. It also covers the mistakes that make a host's choice silently ignored.
This chapter assumes you can already create a module, start a FlutterEngine in the host, and show it with FlutterActivity or FlutterViewController. It also assumes you know how engine caching works. Basic Navigator and named routes in Dart are assumed too.
Two separate choices
The two settings work at different levels.
- A Dart entrypoint is the top-level Dart function the engine runs when it starts. The default is
main(). You can add others, such ascartMain(). - An initial route is a route name string, for example
/cart. The engine hands it to the framework at startup. Your Flutter app then reads it and decides which screen to build first.
An entrypoint chooses which code starts. A route chooses which screen that code shows. You can use either one alone or both together. Use entrypoints when screens need different setup, such as different runApp roots, providers, or initialization. Use routes when one app tree serves several screens.
| Aspect | Dart entrypoint | Initial route |
|---|---|---|
| What it is | A top-level Dart function | A string such as `/cart` |
| Read by | The Dart VM, at engine start | `PlatformDispatcher.defaultRouteName`, read by `MaterialApp` |
| Fixed when | The engine runs the entrypoint | The engine starts, before the first frame |
| Can change later | No, you need a new engine | Yes, with `pushRoute` from the host |
| Typical use | Different app roots or setup | Different screens in one app |
Declaring entrypoints in Dart
An entrypoint must be a top-level function with no required parameters. Annotate every entrypoint except main with @pragma('vm:entry-point'). Release builds use ahead-of-time compilation with tree shaking. Without the annotation, the compiler can remove a function that nothing in Dart calls, and the host then fails to find it.
This module has three entrypoints and one MaterialApp:
import 'package:flutter/material.dart';
void main() => runApp(const ModuleApp());
@pragma('vm:entry-point')
void cartMain() => runApp(const ModuleApp(initialRoute: '/cart'));
@pragma('vm:entry-point')
void profileMain() => runApp(const ModuleApp(initialRoute: '/profile'));
class ModuleApp extends StatelessWidget {
const ModuleApp({super.key, this.initialRoute});
/// Null means "use whatever route the host gave the engine".
final String? initialRoute;
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: initialRoute,
onGenerateInitialRoutes: (name) => [_routeFor(name)],
onGenerateRoute: (settings) => _routeFor(settings.name),
);
}
}
Route<dynamic> _routeFor(String? name) {
final Widget page = switch (name) {
'/cart' => const _Page('Cart'),
'/profile' => const _Page('Profile'),
_ => const _Page('Home'),
};
return MaterialPageRoute<void>(
settings: RouteSettings(name: name),
builder: (_) => page,
);
}
class _Page extends StatelessWidget {
const _Page(this.title);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text(title)));
}
}Two details in this code matter.
First, initialRoute is nullable and has no default of '/'. When MaterialApp.initialRoute is null, the framework uses PlatformDispatcher.instance.defaultRouteName. That value is the route the host set on the engine. If you give your widget a default of '/', the Dart code always overrides the host and the host's route is ignored.
Second, onGenerateInitialRoutes returns a single route. This matters because of how Navigator builds its first stack. For an initial route like /cart/details, the default behavior pushes /, then /cart, then /cart/details. In an add-to-app screen, that leaves a home page underneath the one you asked for. If the user presses back, they see a screen the host never meant to show, and its initState may run, for example a channel call you didn't expect. Returning one route avoids this. The native host then handles back by closing the Flutter view.
Starting an entrypoint from Android
On Android you pass a DartEntrypoint to executeDartEntrypoint. The entrypoint needs the path to the compiled app bundle and the function name. Set the initial route first, because the engine reads it when the entrypoint begins to run:
import android.app.Application
import io.flutter.FlutterInjector
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 bundlePath = FlutterInjector.instance().flutterLoader().findAppBundlePath()
val cartEngine = FlutterEngine(this)
cartEngine.navigationChannel.setInitialRoute("/cart")
cartEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint(bundlePath, "cartMain")
)
FlutterEngineCache.getInstance().put("cart_engine", cartEngine)
}
}If the function lives in a library other than main.dart, use the three-argument constructor, DartEntrypoint(bundlePath, libraryUri, "cartMain"). The library URI is a Dart import URI such as package:my_flutter_module/checkout.dart.
If you don't use a cached engine, FlutterActivity can set the route for you when it creates its own engine:
startActivity(
FlutterActivity
.withNewEngine()
.initialRoute("/profile")
.build(this)
)Starting an entrypoint from iOS
On iOS the engine's run method takes both values. Call it once, before any view controller uses the engine:
import UIKit
import Flutter
import FlutterPluginRegistrant
final class CartEngineHolder {
let engine = FlutterEngine(name: "cart_engine")
init() {
engine.run(withEntrypoint: "cartMain", initialRoute: "/cart")
GeneratedPluginRegistrant.register(with: engine)
}
}Pass nil for the entrypoint to use main. If you create the FlutterViewController without an existing engine, call setInitialRoute("/profile") on it before it first appears. That call has no effect once an engine is already running.
When the values are fixed
The engine reads both values when it starts and cannot change them afterward. This causes the most common surprises when you combine this chapter with engine caching.
- A cached or pre-warmed engine is already running.
FlutterActivity.withCachedEngine("cart_engine").initialRoute(...)is ignored, andFlutterActivity.withCachedEnginehas no entrypoint option at all. The entrypoint and route are whatever you used when you warmed the engine. - On Android, calling
setInitialRouteafterexecuteDartEntrypointdoes nothing useful. The framework has already read the route. - A second
executeDartEntrypointcall on an engine that already runs Dart does not start a new program. Create a second engine or useFlutterEngineGroup, which the multi-screen chapter covers.
The next diagram shows how to decide.
Changing the screen of a running engine
If you reuse one cached engine for several screens, the host can ask the Dart side to navigate. The engine then shows a different route without a restart. On Android, use the engine's navigation channel:
val engine = FlutterEngineCache.getInstance().get("cart_engine")!!
engine.navigationChannel.pushRoute("/profile")
startActivity(FlutterActivity.withCachedEngine("cart_engine").build(this))On iOS, call pushRoute on the view controller:
let vc = FlutterViewController(engine: holder.engine, nibName: nil, bundle: nil)
vc.pushRoute("/profile")
present(vc, animated: true)Keep in mind that pushRoute adds to the navigator stack. If the same engine showed /cart earlier and the user closed that screen, the old route may still be on the stack. Decide how the module resets its navigation state. A common approach is a MethodChannel call from the host that tells Dart to clear the stack, or a route handler that replaces routes instead of pushing them. State kept in Dart objects also survives between launches on a cached engine. This helps performance but can show stale data.
Passing more than a route name
A route string is enough for simple choices. For data such as a product ID, you have three options:
- Encode it in the route.
/product/42works withonGenerateInitialRoutesand a small parser. This is the simplest option and works withpushRoute. - Use entrypoint arguments (Android).
executeDartEntrypoint(entrypoint, listOf("--user=ada"))passes aList<String>, and Dart receives it withvoid main(List<String> args). This is good for startup configuration that doesn't change. - Use a platform channel. Dart asks the host for data after startup, as in the
getUserNameexample from the channels chapter. This works at any time and is the right choice for anything that can change while the engine lives.
Avoid putting secrets, such as tokens, in route strings. Route names can appear in logs and in navigation observers.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Host sets `/cart`, Flutter shows the home page | Dart code hardcodes `initialRoute: '/'` | Make the value nullable and pass it through |
| `Could not resolve main entrypoint function` or a blank view in release only | Missing `@pragma('vm:entry-point')` | Add the annotation to the top-level function |
| Entrypoint works in debug but not from another file | Library URI not supplied | Use the three-argument `DartEntrypoint` with `package:` URI |
| Back from the cart screen shows a home page | Default initial route generation pushes `/` first | Use `onGenerateInitialRoutes` and return one route |
| `initialRoute()` on a cached-engine activity has no effect | Engine already running | Warm the engine with the route, or use `pushRoute` |
| Initial route set but ignored on Android | `setInitialRoute` called after `executeDartEntrypoint` | Call it before |
Choosing between entrypoints and routes
Prefer routes when all screens share the same app setup. They are simpler, they work on running engines, and one MaterialApp holds the shared theme and localization. Add a separate entrypoint when a screen needs its own startup work, a different root widget, or isolation from the rest of the module. Each entrypoint then gets its own engine, so memory use grows with the number of engines. If you need several visible Flutter screens at once, FlutterEngineGroup lets engines share resources and still take their own entrypoint and route.
Exercise
A host warms an engine in Application.onCreate with executeDartEntrypoint(main), and later opens FlutterActivity.withCachedEngine("main_engine").build(this). The team wants the activity to open on /cart, so they add .initialRoute("/cart") to the builder. It still opens the home page. Give two ways to fix it.
Show answer
The engine is already running, so the builder's initial route is ignored. Fix 1: set the route before starting the entrypoint when warming the engine, with engine.navigationChannel.setInitialRoute("/cart") called before executeDartEntrypoint. This fixes the route for that engine, so it only suits an engine used for the cart. Fix 2: keep the generic engine and call engine.navigationChannel.pushRoute("/cart") before starting the activity. The Dart side must also not hardcode initialRoute: '/', and it should handle the route name in onGenerateRoute.
Exercise
Why does a Flutter screen opened at /cart sometimes show a home page when the user presses back, and how do you stop that?
Show answer
By default, Navigator builds the initial stack from the route's path prefixes, so /cart produces / underneath /cart. Back then reveals the home route. Supply onGenerateInitialRoutes and return a list with only the requested route.
Exercise
A new entrypoint checkoutMain works with flutter run -t in debug but the host reports that it cannot find it in a release build. What is the most likely cause, and what else must you supply if the function is in checkout.dart instead of main.dart?
Show answer
The function lacks @pragma('vm:entry-point'), so release tree shaking removed it. Add the annotation. If it is in checkout.dart, the host must also give the library URI, for example package:my_flutter_module/checkout.dart, using the three-argument DartEntrypoint on Android or the libraryURI variant of run on iOS.