Sub topic 2
Creating a Flutter module
This chapter covers the first practical step of add-to-app: creating the Flutter module. You will see what the generator produces, which parts are yours to edit, which are generated, how to run the module on its own, and how to structure the repository so native and Flutter code can live together.
It assumes you can run a Flutter app with the flutter CLI and that you know either Android (Gradle, Activities) or iOS (Xcode, CocoaPods) well enough to open an existing project. The chapters after this one cover wiring the module into a host app.
What a module is
A Flutter module is a Flutter project whose purpose is to be embedded in another app. It is not a standalone app. The Dart code is the same as in any Flutter project. The difference is in the generated native scaffolding and in how the project is packaged.
| Aspect | Regular Flutter app | Flutter module |
|---|---|---|
| Created with | `flutter create my_app` | `flutter create --template module my_module` |
| Native projects | Visible `android/` and `ios/` folders you may edit | Hidden `.android/` and `.ios/` folders that are generated |
| Where native code goes | Directly in `android/` and `ios/` | In the host app, or in plugins |
| Final artifact | An installable app | Code consumed by a host app (source, AAR, or frameworks) |
| Entry point | `main()` | `main()` plus any named entrypoints the host selects |
The module still has to build and run on its own during development. That is why it carries hidden host projects. The Flutter tool uses them for flutter run and as the integration points your real host app imports.
Creating the module
Run the command next to your existing native app, not inside it.
# Run next to (not inside) the existing native app
flutter create --template module my_flutter_module
cd my_flutter_module
flutter runFlutter derives package and bundle identifiers from the project name. You can set them explicitly:
flutter create --template module --org com.example --project-name my_flutter_module my_flutter_module--org sets the reverse-domain prefix. The module name must be a valid Dart package name: lowercase letters, digits, and underscores, not starting with a digit.
Where to put it
The common layout puts the module as a sibling of the native app:
workspace/
my_native_app/ existing Android or iOS app
my_flutter_module/ the Flutter moduleThe sibling layout matters because the integration snippets you will add in later chapters refer to the module by relative path, such as ../my_flutter_module. Both Gradle and CocoaPods resolve these paths from the host project. If your repository structure differs, such as a monorepo with apps/ and packages/, adjust the relative paths. Keep them stable, because every developer and your CI must resolve them identically.
What the generator creates
After the command finishes, the module looks roughly like this:
my_flutter_module/
.android/ generated host project and Flutter library for Android
.ios/ generated host project and Flutter support files for iOS
.metadata
.gitignore
lib/
main.dart
test/
widget_test.dart
pubspec.yaml
pubspec.lock
analysis_options.yaml
README.mdEdit these:
lib/: your Dart code.test/: your tests.pubspec.yaml: dependencies, assets, fonts, and themodulesettings.
Do not edit these by hand:
.android/and.ios/: the Flutter tool regenerates them. Runningflutter pub getafter you changepubspec.yamlrefreshes them, and local edits can be overwritten.
The generated .gitignore excludes .android/ and .ios/ from version control, so the host projects are not committed. Anyone who clones the repository must run flutter pub get in the module before building the host app. Add that step to your onboarding docs and your CI scripts.
The module section of pubspec.yaml
Besides the usual keys, a module's pubspec.yaml has a module block under flutter:. It looks similar to this, though the exact keys vary by Flutter version:
flutter:
uses-material-design: true
module:
androidX: true
androidPackage: com.example.my_flutter_module
iosBundleIdentifier: com.example.myFlutterModuleThe androidPackage and iosBundleIdentifier values name the generated host projects. They are used when you run the module standalone. They do not have to match your real host app's application ID or bundle identifier, because your host app's identity wins when the module is embedded.
Writing module code
The default lib/main.dart is a counter app. You will usually replace it. A module commonly needs three things:
- A default
main()so the module runs withflutter run. - Optional named entrypoints the native host can start by name.
- A way to receive data from the host.
The following module does all three. The next chapters explain the engine and channel mechanics. Here, focus on how the module is structured.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const ModuleApp());
@pragma('vm:entry-point')
void cartMain() => runApp(const ModuleApp(initialRoute: '/cart'));
class ModuleApp extends StatelessWidget {
const ModuleApp({super.key, this.initialRoute = '/'});
final String initialRoute;
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: initialRoute,
routes: {
'/': (_) => const GreetingPage(),
'/cart': (_) => const Scaffold(body: Center(child: Text('Cart'))),
},
);
}
}
class GreetingPage extends StatefulWidget {
const GreetingPage({super.key});
@override
State<GreetingPage> createState() => _GreetingPageState();
}
class _GreetingPageState extends State<GreetingPage> {
static const _channel = MethodChannel('com.example.host/session');
String _name = '...';
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
String? name;
try {
name = await _channel.invokeMethod<String>('getUserName');
} on MissingPluginException {
// Running standalone: no native host registered this channel.
name = null;
}
if (mounted) setState(() => _name = name ?? 'guest');
}
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('Hello, $_name')));
}
}A few details are worth understanding:
@pragma('vm:entry-point')tells the Dart compiler thatcartMainis called from outside Dart. In release builds, the compiler removes functions it thinks nothing calls, a step called tree shaking. Without the annotation, the native host cannot find the function. This is a common cause of an entrypoint that works in debug but fails in release.ModuleApptakes aninitialRouteso one widget tree serves several entrypoints. Each entrypoint decides where the module starts.- The
try/on MissingPluginExceptionblock makes the module usable on its own. When you runflutter runin the module, no native code answersgetUserName, and an unguarded call would throw an unhandled exception. Inside a host app that registered the handler, the call succeeds.
If the host answers with an error, invokeMethod throws a PlatformException. Production code often catches that too.
Running the module on its own
Inside the module directory, flutter run builds the generated .android or .ios host and launches the module on a device or simulator. Use it to iterate on UI and logic that does not depend on the host.
- Choose a device with
flutter run -d <device-id>. List devices withflutter devices. - Standalone, only the default
main()runs. A named entrypoint such ascartMainruns only when a host selects it. To see a route in isolation, temporarily changeinitialRouteinmain(). - Anything that depends on host data, such as a session, falls back to defaults like the
'guest'shown above. Design your module with those fallbacks, or inject test data, so the standalone loop stays useful.
Tests work as in any Flutter project. flutter test runs the contents of test/ with no host, which is another reason to keep UI and logic in Dart and the host dependency behind a thin channel layer.
Dependencies and plugins
You add packages to a module the usual way:
flutter pub add http
flutter pub getPlugins that include native code work in a module. The Flutter tool wires them into the generated host projects, and the host app picks them up through the integration you add later. Pure Dart packages need no native wiring at all.
Native code you write yourself does not go in the module's hidden folders, because they are regenerated. Put host-specific code in the host app. If you need reusable native code shared across apps, build it as a Flutter plugin and depend on it from the module.
Keep two rules in mind:
- If the module and the host app both depend on the same native library, such as a networking SDK, version conflicts appear in the host's build. Plan for this when choosing dependencies.
- After editing
pubspec.yaml, always runflutter pub get, even if you only changed assets. This refreshes the generated host projects.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Host build cannot find the module or its pods | Wrong relative path, or the module was not fetched | Check the path from the host to the module, then run `flutter pub get` in the module |
| `.android` or `.ios` folder missing after a clone | They are gitignored and not committed | Run `flutter pub get` in the module |
| Unhandled `MissingPluginException` when running standalone | Dart calls a channel the standalone host has not registered | Catch the exception or provide a fallback |
| Named entrypoint not found in a release build | Missing `@pragma('vm:entry-point')` | Add the annotation to the entrypoint function |
| Module name rejected by `flutter create` | Invalid Dart package name | Use lowercase letters, digits, and underscores |
What comes next
With the module created and running on its own, the next steps are to understand how a native app hosts Flutter through an engine and a view, and then to connect the module to an Android or iOS project.
Exercise
A teammate clones the repository, opens the Android host app in Android Studio, and the Gradle sync fails because the Flutter module's generated files are missing. The .android/ folder does not exist in their checkout. Why, and what should they do?
Show answer
The module's .gitignore excludes .android/ and .ios/ because they are generated build outputs, so they are not in the repository. The teammate should run flutter pub get in the module directory to regenerate them, then sync Gradle again. Add this step to the onboarding docs and to CI.
Exercise
Your module defines cartMain() without the @pragma('vm:entry-point') annotation. It starts correctly from a debug build of the host app but cannot be found in a release build. Why does this happen, and how do you fix it?
Show answer
Release builds use tree shaking, which removes Dart functions that nothing in Dart appears to call. The native host calls cartMain by name from outside Dart, so the compiler considers it unused and drops it. Annotating the function with @pragma('vm:entry-point') marks it as reachable from outside Dart and keeps it in the release build.
Exercise
When you run flutter run inside the module, the greeting page throws an unhandled MissingPluginException. What causes it, and how does the example code avoid it?
Show answer
The page calls invokeMethod('getUserName') on a channel, but running the module standalone provides no native handler for that channel. The example wraps the call in try/on MissingPluginException and falls back to 'guest', so the module works both standalone and inside a host that registers the handler.