A package to speed up the creation of micro apps structure in Flutter applications (beta version)

Monolithic distribution with independent multiplatform development, inspired in frameworks such as Single SPA, using Event Driven Architecture.

Pub Version CI license PRs Welcome

Screen Shot 2022-02-03 at 00 32 35

⚙ī¸ Define micro app configurations and contracts

Configure the preferences (optional)

      nativeEventsEnabled: true, // If you want to dispatch and listen to events between native(Android/iOS) [default = false]
      nativeNavigationCommandEnabled: true,
      nativeNavigationLogEnabled: true,
      pathSeparator: MicroAppPathSeparator.slash // It joins the routes segments using slash "/" automatically

      // The [MicroPageTransitionType.platform] is a dynamic transition type, 
      // for iOS it will use Cupertino, and for others it will use Material.
      pageTransitionType: MicroPageTransitionType.platform,

      // When pushing routes, if the route is not registered, this will be triggered,
      // and it will abort the navigation
      // [onUnknownRoute] will not be dispatched, since the navigation was aborted.
      // To makes this works, do:
      // - Use root navigator(from MaterialApp) call NavigatorInstance.push...() without context, or
      // - Use MicroAppNavigatorWidget as your nested navigators, or
      // - Use RouterGenerator.onGenerateRoute mixin in your custom navigators
      onRouteNotRegistered: (route, {arguments, type, context}) {
        print('[OnRouteNotRegistered] Route not found: $route, $arguments, $type');

🤝 Exposing all pages through a contract MicroApp

import 'package:micro_routes/exports.dart';

class Application1MicroApp extends MicroApp {

  final routes = Application1Routes();

  List<MicroAppPage> get pages => [

          description: 'The initial page of the micro app 1',
          route: routes.baseRoute.route, 
          pageBuilder: PageBuilder(
            builder: (context, settings) => const Initial(),
            transitionType: MicroPageTransitionType.slideZoomUp

          description: 'Display all buttons of the showcase',
          route: routes.page1, 
          pageBuilder: PageBuilder(
            builder:  (context, settings) => const Page1()

          description: 'The page two',
          route: routes.page2, 
          pageBuilder: PageBuilder(
          builder: (context, settings) {
            final page2Params.fromMap(settings.arguments);
            return Page2(params: page2Params);

🚀 Initialize the micro host, registering all micro apps

  • MyApp(Widget) needs to extends MicroHostStatelessWidget or MicroHostStatefulWidget
  • The MicroHost is the root widget, and it has all MicroApps, and the MicroApps has all Micro Pages and associated MicroRoutes.
void main() {

class MyApp extends MicroHostStatelessWidget { // Use MicroHostStatelessWidget or MicroHostStatefulWidget

  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: NavigatorInstance.navigatorKey, // Required
      onGenerateRoute: onGenerateRoute, // Required - [onGenerateRoute] this is created automatically, so just use it, or override it, if needed.
      initialRoute: '/host_home_page',
      navigatorObservers: [
        NavigatorInstance // [Optional] Add NavigatorInstance here, if you want to get didPop, didReplace and didPush events

  // Register all Host [MicroAppPage]s here
  List<MicroAppPage> get pages => [
          route:  '/host_home_page', 
          pageBuilder: PageBuilder(
            builder: (_, __) => const HostHomePage()
          description: 'The initial page of the application',

  // Register all [MicroApp]s here
  List<MicroApp> get initialMicroApps => [MicroApplication1(), MicroApplication2()];

You can structure your application in many ways, this is one of the ways I usually use it in my projects.


đŸ—ē Create all routes outside the app project

This is just a suggestion of routing strategy (Optional) It's important that all routes are availble out of the projects, avoiding dependencies between micro apps. Create all routes inside a new package, and import it in any project as a dependency. This will make possible to open routes from anywhere in a easy and transparent way.

Create the routing package: flutter create --template=package micro_routes or keep the routes in common package.

// Export all routes
import 'package:flutter_micro_app/flutter_micro_app.dart';

class Application1Routes implements MicroAppBaseRoute {
  MicroAppRoute get baseRoute => MicroAppRoute('application1');

  String get pageExample => path(['example_page']);
  String get page1 => path(['page1']);
  String get page2 => path(['page2','segment1', 'segment2']);

â›ĩī¸ Navigation between pages

For example, you can open a page that is inside other MicroApp, into the root Navigator, in this way(without context):


or you can use the context extension, to get the scoped Navigator `maNav`


or you can use Navigator.of(context), to get scoped Navigator


📲 Open native (Android/iOS) pages, in this way

It needs native implementation, you can see an example inside Android directory

Examples and new modules to Android, iOS and Web soon

// If not implemented, always return null
final isValidEmail = await NavigatorInstance.pushNamedNative<bool>(
    arguments: 'validateEmail:lorem@ipsum.com'
print('Email is valid: $isValidEmail');

Listening to navigation events

// Listen to all flutter navigation events
NavigatorInstance.eventController.flutterLoggerStream.listen((event) {
    logger.d('[flutter: navigation_log] -> $event');

// Listen to all native (Android/iOS) navigation events (if implemented)
NavigatorInstance.eventController.nativeLoggerStream.listen((event) {});

// Listen to all native (Android/iOS) navigation requests (if implemented)
NavigatorInstance.eventController.nativeCommandStream.listen((event) {});

🤲 Handling micro apps events

đŸ—Ŗ Dispatches events to all handlers that listen to channels 'user_auth'

  const MicroAppEvent(
    name: 'my_event',
    channels: ['user_auth'])

đŸ—Ŗ Dispatches events to handlers that listen to String event type

  const MicroAppEvent(
    name: 'my_event',
    payload: 'some string here')

đŸ—Ŗ Dispatches events to handlers that listen to MyCustomClass event type, and channels 'user_auth' and 'wellcome'

  const MicroAppEvent(
    name: 'my_event',
    payload: MyCustomClass(userName: 'Emanuel Braz'),
    channels: ['user_auth', 'wellcome']

Note Use Json String for agnostic platform purposes, or HashMap for Kotlin, Dictionary for Swift or java.util.HashMap for Java.

When running javascript, use JSON.stringify({}). see fma_webview_flutter

Dispatching event using Json.
 "name": "", // Optional
 "payload": {}, // Optional
 "distinct": true, // Optional
 "channels": [], // Optional
 "version": "1.0.0", // Optional
 "datetime": "2020-01-01T00:00:00.000Z" // Optional
Dispatching event from native(Android), using Kotlin
val payload: MutableMap<String, Any> = HashMap()
payload["platform"] = "Android"

val arguments: MutableMap<String, Any> = HashMap()
arguments["name"] = "event_from_native"
arguments["payload"] = payload
arguments["distinct"] = true
arguments["channels"] = listOf("abc", "chatbot")
arguments["version"] = "1.0.0"
arguments["datetime"] = "2020-01-01T00:00:00.000Z"

appEventChannelMessenger.invokeMethod("app_event", arguments)

🌐 It is possible to wait for other micro apps to respond to the event you issued, but make sure someone else will respond to your event, or use timeout parameter to set a wait limit time, otherwise you will wait forever đŸ˜ĸ

remember, with great power comes great responsibility

.getFirstResult() will return the first response(fastest) among all micro apps that eventually can respond to this same event.

For example, if you request a JWT token to all micro apps(broadcast), the first response(if more than one MA can respond) will end up your request with the resultSucces value or with a resultError, from the fastest micro app.

  final result = await MicroAppEventController()
    .emit(MicroAppEvent<Map<String, String>>(
      name: 'get_jwt',
      payload: const {'userId': 'ABC123'},
      channels: const ['jwt'],
  ).getFirstResult(); // This will return the first response(fastest) among all micro app that eventually can respond to this same the event


Later, when some micro app that is listening to same channel get triggered, it can answer success or error.

// results success
event.resultSuccess(['success message by Wally West', 'your token, Sir.']);

// results error
event.resultError(['error message by Barry Allen', 'my bad đŸ¤Ļ']);

// Who will respond faster? native? flutter?
// If you don't want to take that risk, just deal with the List<Future> response.

Dealing with errors and timeout:

timeout is an optional parameter, use only if you intends to wait for the event to be sent back, otherwise this can throw uncaught timeout exceptions.

If you need an EDA approach, use the MicroAppEventHandler as a consumer, in order to get all event dispatched by producers.

try {
  final result = await MicroAppEventController()
          name: 'event_from_flutter',
          payload: 'My payload',
        timeout: const Duration(seconds: 2)
  logger.d('Result is: $result');
} on TimeoutException catch (e) {
      'The native platform did not respond to the request',
      error: e);
} on PlatformException catch (e) {
      'The native platform respond to the request with some error',
      error: e);
} on Exception {
  logger.e('Generic Error');


final futures = MicroAppEventController().emit(
      name: 'show_snackbar',
      payload: 'Hello World!',
      channels: const ['show_snackbar'],
    timeout: const Duration(seconds: 3)

  .then((value) => {
    // 2 - this line will be executed later
            '** { You can capture data asyncronously later } **')
  .catchError((error) async {
      '** { You can capture errors asyncronously later } **',
      error: error);
  return <dynamic>{};

  // 1 - this line will be executed first
logger.d('** { You do not need to wait for a TimeoutException } **');

đŸĻģ Listen to events (MicroApps)

Use the mixin HandlerRegisterMixin in order to get the method registerEventHandler

class MyMicroApplication extends MicroApp with HandlerRegisterMixin {
  MyMicroApplication() {
    // It listen to all events
    // Avoid using such a generic handler, prefer to use handlers by type 
    // and with channels for a granular and specialized treatment
        (event) => logger.d([ event.name, event.payload])


Some example scenarios:

// It listen to events with channels "chatbot" and "user_auth"
  MicroAppEventHandler((event) {
    // User auth feature, asked to show a popup :)
  }, channels: ['chatbot', 'user_auth']);

// It listen to events with type String (only)
  MicroAppEventHandler((event) {
    // Use .cast() to automatically cast the payload data to String? type

// It will be fired for every event, even if the value is the same (distinct = false)
  MicroAppEventHandler((event) {
  }, distinct: false);

Listen to events inside widgets (If need BuildContext or if you need to unregister event handlers automatically)

It can be achieved, registering the event handlers and unregistering them manually, but is advised to use a mixin called HandlerRegisterStateMixin to dispose handlers automatically when widget is disposed

Using mixin HandlerRegisterStateMixin example:

class MyWidgetState extends State<MyWidget> with HandlerRegisterStateMixin {

  void initState() {
      MicroAppEventHandler<String>((event) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(event.cast())));
    }, channels: const ['show_snackbar'], distinct: false));


  Widget build(BuildContext context) {
    return Container();

Managing event handlers

MicroAppEventController().unregisterHandler(id: '123');
MicroAppEventController().unregisterHandler(handler: handlerInstance);
MicroAppEventController().unregisterHandler(channels: ['user_auth']);

đŸĻģ Initiating an event subscription anywhere in the application

Take care when registering an event handler directly in the controller, as you will need to manually unregister them when they are no longer needed.

Always prefer to use the HandlerRegisterStateMixin and HandlerRegisterMixin mixins, as they take care to unregister event handlers when they are no longer useful.

Using subscription

final subscription = MicroAppEventController().stream.listen((MicroAppEvent event) {

// later, in dispose method of the widget
void dispose() {

Using handler

MicroAppEventController().registerHandler(MicroAppEventHandler(id: '1234'));

// later, in dispose method of the widget
void dispose() {
    MicroAppEventController().unregisterHandler(id: '1234');

🏭 Using the pre-built widget MicroAppWidgetBuilder to display data on the screen

It can be used to show visual info on the screen. In this example, it shows a button and the label changes when user clicks on the button

ℹī¸ When user dispatched an event in the same channel that the widget is listening to, the widget redraw the updated info on the screen.

  initialData: MicroAppEvent(name: 'my_event', payload: 0),
  channels: const ['widget_channel'],
  builder: (context, eventSnapshot) {
    if (eventSnapshot.hasError) return const Text('Error');
    return ElevatedButton(
      child: Text('Widget count = ${eventSnapshot.data?.payload}'
      onPressed: () {
            name: 'my_event',
            payload: ++count,
            channels: const ['widget_channel']));

📝 Overriding onGenerateRoute method

If it fails to get a page route, ask for native(Android/iOS/Desktop/Web) to open the page

  Route? onGenerateRoute(RouteSettings settings, {bool? routeNativeOnError}) {
    //! If you wish native app receive requests to open routes, IN CASE there
    //! is no route registered in Flutter, please set [routeNativeOnError: true]
    return super.onGenerateRoute(settings, routeNativeOnError: true);

If it fails to get a page route, show a default error page

  Route? onGenerateRoute(RouteSettings settings, {bool? routeNativeOnError}) {
    final pageRoute = super.onGenerateRoute(settings, routeNativeOnError: false);

    if (pageRoute == null) {
       // If pageRoute is null, this route wasn't registered(unavailable)
       return MaterialPageRoute(
           builder: (_) => Scaffold(
                 appBar: AppBar(),
                 body: const Center(
                   child: Text('Page Not Found'),
    return pageRoute;

âĢ¸ Nested Navigators

It's possible to use a MicroAppBaseRoute inside a nested navigator MicroAppNavigatorWidget

IMPORTANT: use the context.maNav to navigate:

final baseRoute = ApplicationRoutes();

    microBaseRoute: baseRoute,
    initialRoute: baseRoute.page1

// later, inside [page1]
final settings = MicroAppNavigator.getInitialRouteSettings(context);
final settings = context.maNav.getInitialRouteSettings();

//IMPORTANT: use the context to navigate

It can be registered inside MicroPages list.

final routes = ApplicationRoutes();

List<MicroAppPage> get pages => [
      route: routes.baseRoute.route,
      description: 'The nested navigator',
      pageBuilder: PageBuilder(
        builder: (context, arguments) => 
            microBaseRoute: baseRoute,
            initialRoute: Application2Routes().page1)

📊 Micro Board

The Micro Board (dashboard) enables you to inspect all micro apps, routes and event handlers.

  • Inspect which handler channels are duplicated
  • Inspect the types and amount of handlers and their channels per micro app
  • Inspect the types and amount of handlers and their channels by Widget
  • Inspect orphaned handlers
  • Inspect all registered routes from the application

Show Micro Board button (longPress hides the button, and click opens the Micro Board)
This will create a draggable floating button, that enables you to open the Micro Board. By default it is not displayed in release mode.




🌐 Micro Web (Webview Controllers)

Take a look at https://pub.dev/packages/fma_webview_flutter

📎 The following table shows how Dart values are received on the platform side and vice versa

boolBooleanNSNumber(value: Bool)java.lang.Boolean
intIntNSNumber(value: Int32)java.lang.Integer
int, if 32 bits not enoughLongNSNumber(value: Int)java.lang.Long
doubleDoubleNSNumber(value: Double)java.lang.Double
Uint8ListByteArrayFlutterStandardTypedData(bytes: Data)byte[]
Int32ListIntArrayFlutterStandardTypedData(int32: Data)int[]
Int64ListLongArrayFlutterStandardTypedData(int64: Data)long[]
Float32ListFloatArrayFlutterStandardTypedData(float32: Data)float[]
Float64ListDoubleArrayFlutterStandardTypedData(float64: Data)double[]

👨‍đŸ’ģ👨‍đŸ’ģ Contributing

Contributions of any kind are welcome!