GetIt Modular with AutoRoute 🧩+🚗
A companion package that seamlessly integrates get_it_modular with auto_route, providing a powerful and convenient pattern for modular routing and scoped dependency injection.
Note: This package requires and builds upon
get_it_modular. Please see the main package documentation for core concepts likeModuleContractandModuleScope.
What It Does
While get_it_modular is router-agnostic, setting up modular routes and scope wrappers for each module can involve some boilerplate. This package provides convenient helpers to make that process effortless, allowing you to define your routes directly within your modules.
Installation
Add the necessary packages to your pubspec.yaml file:
dependencies:
get_it_modular_with_auto_route: ^1.0.0
auto_route: ^10.1.2
get_it: ^8.2.0
dev_dependencies:
auto_route_generator: ^10.2.4
build_runner: ^2.4.9
Getting Started
This package streamlines the setup process into a few simple steps.
Step 1: Define Routes in Your Module
First, add a routes getter to your ModuleContract implementations. This package also provides the ModuleScopeWrapper out of the box.
// lib/features/events/event_module.dart
import 'package:auto_route/auto_route.dart';
import 'package:get_it_modular/get_it_modular.dart';
import 'package:get_it_modular_with_auto_route/get_it_modular_with_auto_route.dart';
class EventModule extends ModuleContract {
@override
void registerDependencies() {
// Register dependencies as usual...
}
@override
List<AutoRoute> get routes => [
AutoRoute(
path: '/events',
page: ModuleScopeWrapper<EventModule>.page, // Use the provided wrapper
children: [
AutoRoute(path: '', page: EventListRoute.page),
AutoRoute(path: ':id', page: EventDetailsRoute.page),
],
),
];
}
Step 2: Create Your AppRouter
Create your router by extending RootStackRouter and using the WithModuleRoutes mixin provided by this package.
// lib/router.dart
import 'package:auto_route/auto_route.dart';
import 'package:get_it_modular_with_auto_route/get_it_modular_with_auto_route.dart';
part 'router.gr.dart'; // Run build_runner to generate
@AutoRouterConfig()
class AppRouter extends _$AppRouter with WithModuleRoutes {}
Step 3: Initialize Everything
In your main app setup, register your modules and then initialize the router by passing the list of modules to its init method.
// lib/main.dart
import 'package:get_it/get_it.dart';
Future<void> main() async {
// 1. Register modules as singletons
GetIt.I.registerLazySingleton(() => MainModule());
GetIt.I.registerLazySingleton(() => EventModule());
// 2. Initialize the router with all modules
final appRouter = AppRouter();
final allModules = [GetIt.I.get<MainModule>(), GetIt.I.get<EventModule>()];
appRouter.init(modules: allModules);
// 3. Run your app
runApp(MyApp(router: appRouter));
}
That's it! Your router is now automatically configured with all the routes defined inside your modules, and each module's routes are correctly wrapped in their ModuleScope.