=============== LIBRARY RULES =============== From library maintainers: - Use GoRouter for navigation — always configure it through Modugo's module system, not directly. For GoRouter-specific questions use Context7 library /websites/pub_dev_go_router - Use GetIt for DI — binds are registered per module via binds(). For GetIt-specific patterns use Context7 library /fluttercommunity/get_it - Define modules implementing IModule with imports(), binds(), and routes() - Use ChildRoute, ModuleRoute, ShellModuleRoute, StatefulShellModuleRoute, or AliasRoute - Prefer the declarative DSL: child(), module(), alias(), shell(), statefulShell() - Protect routes with guards implementing IGuard — guards propagate to sub-routes automatically - Access DI via Modugo.i.get(), i.get(), or context.read() inside widgets ### Complete Module Configuration Example Source: https://github.com/bed72/modugo/blob/master/doc/documentation/guards/index.md A full example showing dependency registration and route protection using propagateGuards. ```dart final class AppModule extends Module { @override void binds() { i ..registerSingleton(AuthRepositoryImpl()) ..registerSingleton(UserService()); } @override List routes() => [ // Rota publica (sem guard) route('/login', child: (_, _) => const LoginPage()), // Rotas protegidas ...propagateGuards( guards: [AuthGuard(repository: i.get())], routes: [ route('/', child: (_, _) => const HomePage()), module('/profile', ProfileModule()), module('/admin', AdminModule()), // AdminModule pode ter seus proprios guards ], ), ]; } ``` -------------------------------- ### Full Example of AppModule Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md An example demonstrating the usage of various Modugo DSL methods within an AppModule to define a complete routing structure. ```APIDOC ## Example Complete ### Description Demonstrates the usage of various Modugo DSL methods within an AppModule. ### Method N/A (DSL usage within a class) ### Endpoint N/A ### Parameters N/A ### Request Example ```dart final class AppModule extends Module { @override List routes() => [ child(child: (_, _) => const HomePage()), module(module: AuthModule()), alias(from: '/cart/:id', to: '/order/:id'), shell( builder: (_, _, child) => MainShell(child: child), routes: [ child(path: '/dashboard', child: (_, _) => const DashboardPage()), child(path: '/settings', child: (_, _) => const SettingsPage()), ], ), statefulShell( builder: (_, _, shell) => BottomBarWidget(shell: shell), routes: [ module(module: FeedModule()), module(module: ProfileModule()), ], ), ]; } ``` ### Response #### Success Response (200) N/A (This is a configuration example) #### Response Example N/A ``` -------------------------------- ### Complete Example: Product View Tracking Source: https://github.com/bed72/modugo/blob/master/doc/documentation/events/index.md This example demonstrates defining a `ProductViewedEvent`, emitting it when a product is viewed, and listening for it in an `AnalyticsModule` to track the event. It also shows listening for `RouteChangedEventModel` within the same module. ```dart // Definição do evento final class ProductViewedEvent { final String productId; ProductViewedEvent(this.productId); } // Emissão (em qualquer lugar) Event.emit(ProductViewedEvent('prod-42')); // Escuta no módulo de analytics final class AnalyticsModule extends Module with IEvent { @override void listen() { on((event) { Analytics.trackProductView(event.productId); }); on((event) { Analytics.trackPageView(event.location); }); } @override List routes() => []; } ``` -------------------------------- ### Install Modugo Skills Source: https://github.com/bed72/modugo/blob/master/doc/documentation/ai/index.md Install skills via the ctx7 CLI or manually by copying the skill directory into your project. ```bash # Instalar todas as skills do Modugo interativamente ctx7 skills install /bed72/Modugo # Instalar uma skill específica ctx7 skills install /bed72/Modugo create-module ``` ```text skills/ └── create-module/ └── SKILL.md ``` -------------------------------- ### Run Flutter Pub Get Source: https://github.com/bed72/modugo/blob/master/doc/index.md Command to fetch the added dependency. ```bash flutter pub get ``` -------------------------------- ### Install Modugo Source: https://github.com/bed72/modugo/blob/master/doc/index.md Add the dependency to your pubspec.yaml file. ```yaml dependencies: modugo: ^4.2.6 ``` -------------------------------- ### Complete Module Definition Example Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md A full implementation of a Module class using the DSL to define various route types. ```dart final class AppModule extends Module { @override List routes() => [ child(child: (_, _) => const HomePage()), module(module: AuthModule()), alias(from: '/cart/:id', to: '/order/:id'), shell( builder: (_, _, child) => MainShell(child: child), routes: [ child(path: '/dashboard', child: (_, _) => const DashboardPage()), child(path: '/settings', child: (_, _) => const SettingsPage()), ], ), statefulShell( builder: (_, _, shell) => BottomBarWidget(shell: shell), routes: [ module(module: FeedModule()), module(module: ProfileModule()), ], ), ]; } ``` -------------------------------- ### Modugo Installation Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Instructions on how to add Modugo to your Flutter project's dependencies. ```APIDOC ## Modugo Installation Add Modugo to your `pubspec.yaml` file: ```yaml dependencies: modugo: ^4.2.6 ``` Then run: ```bash flutter pub get ``` ``` -------------------------------- ### Create Root Module (AppModule) Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Define the root module for your application, aggregating submodules and global dependencies. This example registers an AuthService as a singleton. ```dart final class AppModule extends Module { @override void binds() { i.registerSingleton(AuthService()); } @override List routes() => [ route('/', child: (_, _) => const HomePage()), module('/auth', AuthModule()), module('/profile', ProfileModule()), ]; } ``` -------------------------------- ### Common Guard Implementations Source: https://github.com/bed72/modugo/blob/master/doc/documentation/guards/index.md Examples of guards for authentication, role-based access, and side-effect logging. ```dart final class AuthGuard implements IGuard { @override FutureOr call(BuildContext context, GoRouterState state) async { final isLoggedIn = await checkAuth(); return isLoggedIn ? null : '/login'; } } ``` ```dart final class AdminGuard implements IGuard { @override FutureOr call(BuildContext context, GoRouterState state) async { final user = context.read().currentUser; return user.isAdmin ? null : '/unauthorized'; } } ``` ```dart final class AnalyticsGuard implements IGuard { @override FutureOr call(BuildContext context, GoRouterState state) { Analytics.logPageView(state.uri.path); return null; // sempre permite acesso } } ``` -------------------------------- ### Modugo Skills Directory Structure Source: https://github.com/bed72/modugo/blob/master/doc/documentation/ai/index.md The directory structure for installed skills, where each folder contains a SKILL.md file with instructions for the AI. ```text skills/ ├── create-module/ │ └── SKILL.md ├── create-route/ │ └── SKILL.md ├── add-guard/ │ └── SKILL.md └── register-dependency/ └── SKILL.md ``` -------------------------------- ### Add Modugo Dependency Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Add the Modugo dependency to your pubspec.yaml file and run flutter pub get to install it. ```yaml dependencies: modugo: ^4.2.6 ``` ```bash flutter pub get ``` -------------------------------- ### Invoke Modugo Skills Source: https://github.com/bed72/modugo/blob/master/doc/documentation/ai/index.md Use the installed skills in your AI prompts to scaffold modules or apply guards. ```text use create-module skill to scaffold a ProfileModule with AuthGuard ``` ```text use add-guard skill to protect all routes in AdminModule ``` -------------------------------- ### Modugo Logger Output Format Source: https://github.com/bed72/modugo/blob/master/doc/documentation/utilities/index.md Example of the formatted log output from Modugo's internal logger, including timestamp, log level, and message. ```plaintext [14:30:45][MODULE] AppModule binds registered [14:30:45][INJECT] AuthService registered as singleton [14:30:46][NAVIGATION] Navigated to /home ``` -------------------------------- ### Accessing Location Segments with GoRouterStateExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Demonstrates how to get the path segments of the current location as a list using `locationSegments` from GoRouterStateExtension. ```dart final segments = state.locationSegments; // '/profile/settings' → ['profile', 'settings'] ``` -------------------------------- ### Instalar MkDocs Source: https://github.com/bed72/modugo/blob/master/doc/README.md Instala o MkDocs e o tema Material via pip. ```bash pip install mkdocs ``` ```bash pip install mkdocs-material ``` -------------------------------- ### Inicializar projeto MkDocs Source: https://github.com/bed72/modugo/blob/master/doc/README.md Cria a estrutura de arquivos necessária para um novo projeto MkDocs no diretório atual. ```bash mkdocs new . ``` -------------------------------- ### Basic and Named Navigation with ContextNavigationExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Demonstrates basic and named navigation using the `go` and `goNamed` methods provided by the ContextNavigationExtension. ```dart context.go('/home'); context.push('/product/42'); ``` ```dart context.goNamed('product', pathParameters: {'id': '42'}); context.pushNamed('settings', queryParameters: {'tab': 'privacy'}); ``` -------------------------------- ### Utilizar Transition.builder Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/transitions.md Cria um builder de transição personalizado com um callback de configuração para logging ou efeitos colaterais. ```dart final transitionBuilder = Transition.builder( type: TypeTransition.slideUp, config: () => debugPrint('Aplicando transição'), ); ``` -------------------------------- ### Accessing Dependencies Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Demonstrates the different methods to access registered dependencies using Modugo's dependency injection. ```APIDOC ## Accessing Dependencies Three equivalent ways to access dependencies: ```dart // Via module injector final service = i.get(); // Via Modugo class final service = Modugo.i.get(); // Via BuildContext final service = context.read(); ``` ``` -------------------------------- ### Emit Events Source: https://github.com/bed72/modugo/blob/master/doc/documentation/events/index.md Use `Event.emit()` to trigger an event. This method is globally accessible and does not require any specific setup. ```dart Event.emit(UserLoggedInEvent('user-123')); Event.emit(CartUpdatedEvent(5)); ``` -------------------------------- ### Executar servidor local Source: https://github.com/bed72/modugo/blob/master/doc/README.md Inicia o servidor de desenvolvimento do MkDocs em um endereço e porta específicos. ```bash mkdocs serve -a 127.0.0.1:8080 ``` -------------------------------- ### Ativar ambiente virtual Source: https://github.com/bed72/modugo/blob/master/doc/README.md Ativa o ambiente virtual em sistemas baseados em Unix. ```bash source .venv/bin/activate ``` -------------------------------- ### Gerenciamento Manual de Dependências Source: https://github.com/bed72/modugo/blob/master/doc/documentation/migration/index.md Exemplo de como realizar o registro e descarte manual de dependências na v3.x. ```dart // Registrar i.registerSingleton(MyService()); // Quando não precisar mais (se necessário) i.unregister(); ``` -------------------------------- ### Desativar ambiente virtual Source: https://github.com/bed72/modugo/blob/master/doc/README.md Encerra a sessão do ambiente virtual ativo. ```bash deactivate ``` -------------------------------- ### Synchronous and Asynchronous Dependency Reading with ContextInjectionExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Illustrates accessing synchronous and asynchronous dependencies registered with GetIt using `read` and `readAsync` from ContextInjectionExtension. ```dart final service = context.read(); ``` ```dart final db = context.read(instanceName: 'primary'); ``` ```dart final api = await context.readAsync(); ``` -------------------------------- ### Modugo.configure() Parameters Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Detailed explanation of the parameters available for the `Modugo.configure()` method. ```APIDOC ## Parameters for `Modugo.configure()` | Parameter | Type | Default | Description | |---|---|---|---| | `module` | `Module` | **required** | The root module of the application | | `initialRoute` | `String` | `'/'` | The initial route | | `pageTransition` | `TypeTransition` | `fade` | Default transition for all routes | | `debugLogDiagnostics` | `bool` | `false` | Enables internal Modugo logs | | `debugLogDiagnosticsGoRouter` | `bool` | `false` | Enables GoRouter logs | | `observers` | `List?` | `null` | Navigation observers | | `navigatorKey` | `GlobalKey?` | `null` | Global navigator key | | `redirect` | `FutureOr Function(...)` | `null` | Global redirect function | | `errorBuilder` | `Widget Function(...)` | `null` | Custom error page builder | | `onException` | `void Function(...)` | `null` | Exception callback | | `refreshListenable` | `Listenable?` | `null` | Listenable for router refresh | | `redirectLimit` | `int` | `2` | Redirect limit before error | | `extraCodec` | `Codec?` | `null` | Codec for extra serialization | | `enableIOSGestureNavigation` | `bool` | `true` | Enables native iOS swipe-back gesture globally. Can be overridden per route via `ChildRoute.iosGestureEnabled`. ``` -------------------------------- ### Matching Routes and Extracting Parameters with ContextMatchExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Demonstrates finding a matching route and extracting parameters from a location string using `matchingRoute` and `matchParams` from ContextMatchExtension. ```dart final route = context.matchingRoute('/user/42'); if (route != null) { debugPrint('Rota encontrada: ${route.name}'); } ``` ```dart final params = context.matchParams('/user/42'); final userId = params?['id']; // '42' ``` -------------------------------- ### ContextNavigationExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Simplifies GoRouter navigation operations directly from the BuildContext. ```APIDOC ## ContextNavigationExtension ### Description Provides methods to perform navigation, stack management, and router access directly from the BuildContext. ### Methods - **go(location, {extra})** - Navigates to the specified path. - **goNamed(name, {pathParameters, queryParameters, extra, fragment})** - Navigates by route name. - **push(location, {extra})** - Pushes a new route onto the stack. - **pushNamed(name, {pathParameters, queryParameters, extra})** - Pushes a new route by name. - **pop([result])** - Removes the current route from the stack. - **canPop()** - Checks if navigation back is possible. - **canPush(location)** - Checks if the path exists in the router. - **replace(location, {extra})** - Replaces the current route. - **pushReplacement(location, {extra})** - Pushes a route replacing the current one. - **replaceNamed(name, {pathParameters, queryParameters, extra})** - Replaces the current route by name. - **pushReplacementNamed(name, {...})** - Pushes a route by name replacing the current one. - **reload()** - Reloads the current route. - **replaceStack(paths)** - Replaces the entire navigation stack. - **goRouter** - Accesses the GoRouter instance. ``` -------------------------------- ### Create a ModuleRoute with module() Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md Connects submodules to establish a hierarchical navigation structure. ```dart module( module: AuthModule(), name: 'auth', parentNavigatorKey: myKey, ); ``` -------------------------------- ### Utility Mixins and Route Compilers Source: https://github.com/bed72/modugo/blob/master/README.md Use AfterLayoutMixin for post-frame execution, CompilerRoute for path manipulation, and configure global logging. ```dart class _MyScreenState extends State with AfterLayoutMixin { @override Future afterFirstLayout(BuildContext context) async { context.read().loadData(); } } ``` ```dart final route = CompilerRoute('/user/:id'); route.match('/user/42'); // true route.extract('/user/42'); // {'id': '42'} route.build({'id': '42'}); // '/user/42' ``` ```dart await Modugo.configure(module: AppModule(), debugLogDiagnostics: true); ``` -------------------------------- ### Recommended Project Structure Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md A suggested directory structure for organizing modules, pages, and components in a Modugo project. ```APIDOC ## Recommended Project Structure ``` /lib /modules /home home_page.dart home_module.dart /profile profile_page.dart profile_module.dart /auth auth_page.dart auth_module.dart app_module.dart app_widget.dart main.dart ``` Each module encapsulates its own routes, dependencies, and pages, promoting organized and decoupled code. ``` -------------------------------- ### Accessing the Router Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md How to access the configured router instance within your application. ```APIDOC ## Accessing the Router There are two ways to access the configured router: ```dart // Via global getter modugoRouter // Via Modugo class Modugo.routerConfig // For imperative navigation, use the global key: modugoNavigatorKey.currentState?.push(...); ``` ``` -------------------------------- ### Create a ShellModuleRoute with shell() Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md Groups multiple routes under a shared layout or scaffold. ```dart shell( builder: (_, _, child) => AppScaffold(child: child), routes: [ route('/feed', child: (_, _) => const FeedPage()), route('/settings', child: (_, _) => const SettingsPage()), ], observers: [MyObserver()], navigatorKey: shellKey, parentNavigatorKey: parentKey, pageBuilder: (_, _, child) => MaterialPage(child: child), ); ``` -------------------------------- ### Registrar dependências em um módulo Source: https://github.com/bed72/modugo/blob/master/doc/documentation/injection/index.md Utilize o método binds() dentro de uma classe que estende Module para registrar serviços usando o injetor i. ```dart final class HomeModule extends Module { @override List imports() => [CoreModule()]; // importa outros módulos se necessário @override List routes() => [ ChildRoute(path: '/', child: (context, state) => const HomePage()), ]; @override void binds() { i ..registerSingleton(ServiceRepository.instance) // singleton ..registerLazySingleton(OtherServiceRepositoryImpl.new); // lazy singleton } } ``` -------------------------------- ### Accessing Dependencies Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Illustrates three equivalent methods for accessing registered dependencies: using the module injector, the Modugo class, or the BuildContext. ```dart // Via injector do módulo final service = i.get(); // Via classe Modugo final service = Modugo.i.get(); // Via BuildContext final service = context.read(); ``` -------------------------------- ### Configure Modugo in main.dart Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Initialize Modugo by calling Modugo.configure with your root module and initial route in the main function. ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Modugo.configure( module: AppModule(), initialRoute: '/', ); runApp(const AppWidget()); } ``` -------------------------------- ### Dependency Injection Configuration and Access Source: https://github.com/bed72/modugo/blob/master/README.md Register services within a module's binds method and access them using the provided lookup methods. ```dart final class HomeModule extends Module { @override void binds() { i ..registerSingleton(ServiceRepository()) ..registerLazySingleton(ApiClient.new); } } ``` ```dart final service = i.get(); final service = Modugo.i.get(); final service = context.read(); ``` -------------------------------- ### Definir ShellModuleRoute Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Cria uma área de navegação interna para layouts com menus ou abas. ```dart final class HomeModule extends Module { @override List routes() => [ ShellModuleRoute( builder: (context, state, child) => PageWidget(child: child), routes: [ ChildRoute(path: '/user', child: (_, _) => const UserPage()), ChildRoute(path: '/config', child: (_, _) => const ConfigPage()), ChildRoute(path: '/orders', child: (_, _) => const OrdersPage()), ], ), ]; } ``` -------------------------------- ### Configurar transição global Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/transitions.md Define a transição padrão para todas as rotas do aplicativo através do método Modugo.configure(). ```dart await Modugo.configure( module: AppModule(), pageTransition: TypeTransition.slideLeft, ); ``` -------------------------------- ### Comparação de Gerenciamento de Dependências (v2.x vs v3.x) Source: https://github.com/bed72/modugo/blob/master/doc/documentation/migration/index.md Demonstra a mudança no comportamento de descarte automático de dependências entre as versões 2.x e 3.x. ```dart // Dependências eram descartadas automaticamente ao sair do módulo final class HomeModule extends Module { @override void binds() { // Registrado e descartado automaticamente i.registerSingleton(HomeController()); } } ``` ```dart // Dependências vivem até o app encerrar final class HomeModule extends Module { @override void binds() { // Registrado uma vez, vive para sempre i.registerSingleton(HomeController()); } } ``` -------------------------------- ### Create Root Module Source: https://github.com/bed72/modugo/blob/master/doc/index.md Define the root module by extending the Module class and implementing binds and routes. ```dart final class AppModule extends Module { @override void binds() { i.registerSingleton(AuthService()); } @override List routes() => [ route('/', child: (_, _) => const HomePage()), module('/profile', ProfileModule()), ]; } ``` -------------------------------- ### Configurar navegação global Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Define o comportamento padrão de navegação para todo o aplicativo. ```dart await Modugo.configure( module: AppModule(), enableIOSGestureNavigation: false, // desativa para todas as rotas por padrão ); ``` -------------------------------- ### Imperative Navigation Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Shows how to perform imperative navigation using the global navigator key provided by Modugo. ```dart modugoNavigatorKey.currentState?.push(...); ``` -------------------------------- ### Create a StatefulShellModuleRoute with statefulShell() Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md Enables navigation with multiple independent stacks, typically used for bottom navigation bars. ```dart statefulShell( builder: (_, _, shell) => BottomBarWidget(shell: shell), routes: [ module('/home', HomeModule()), module('/profile', ProfileModule()), ], key: shellKey, parentNavigatorKey: parentKey, ); ``` -------------------------------- ### Implement a Shell Page Widget Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Creates a layout with a persistent navigation bar at the bottom using a Scaffold and Column. ```dart class PageWidget extends StatelessWidget { final Widget child; const PageWidget({super.key, required this.child}); @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Expanded(child: child), Row( children: [ IconButton(icon: const Icon(Icons.person), onPressed: () => context.go('/user')), IconButton(icon: const Icon(Icons.settings), onPressed: () => context.go('/config')), IconButton(icon: const Icon(Icons.shopping_cart), onPressed: () => context.go('/orders')), ], ), ], ), ); } } ``` -------------------------------- ### Criar ambiente virtual Python Source: https://github.com/bed72/modugo/blob/master/doc/README.md Cria um diretório de ambiente virtual chamado .venv no diretório atual. ```bash python3 -m venv .venv ``` -------------------------------- ### Importação de Módulos e Injeção de Dependência Source: https://github.com/bed72/modugo/blob/master/doc/documentation/modules/index.md Demonstra o uso do método imports para reutilizar dependências de outros módulos e registrar controladores locais. ```dart final class HomeModule extends Module { @override List imports() => [SharedModule()]; @override void binds() { // SharedModule já foi registrado, podemos usar suas dependências i.registerLazySingleton( () => HomeController(i.get()), ); } @override List routes() => [ route('/', child: (_, _) => const HomePage()), ]; } ``` -------------------------------- ### Comparar Modugo com GetIt Source: https://github.com/bed72/modugo/blob/master/doc/documentation/injection/index.md Demonstração da similaridade sintática entre o registro de dependências no GetIt e no Modugo. ```dart // GetIt final getIt = GetIt.instance; getIt.registerSingleton(ServiceRepository.instance); // Modugo i.registerSingleton(ServiceRepository.instance); ``` -------------------------------- ### Definição do Módulo Raiz (AppModule) Source: https://github.com/bed72/modugo/blob/master/doc/documentation/modules/index.md Exemplo de como registrar dependências globais e compor rotas de sub-módulos no módulo principal. ```dart final class AppModule extends Module { @override void binds() { i.registerSingleton(AuthService()); } @override List routes() => [ module('/home', HomeModule()), module('/chat', ChatModule()), module('/profile', ProfileModule()), ]; } ``` -------------------------------- ### Configure Context7 MCP for AI Tools Source: https://github.com/bed72/modugo/blob/master/doc/documentation/ai/index.md Add the Context7 MCP server configuration to your AI tool's settings file to enable Modugo documentation injection. ```json { "mcpServers": { "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp"] } } } ``` ```json { "github.copilot.chat.mcp.enabled": true, "mcp": { "servers": { "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp"] } } } } ``` ```json { "mcpServers": { "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp"] } } } ``` -------------------------------- ### Create a feature module Source: https://github.com/bed72/modugo/blob/master/README.md Encapsulate dependencies and routes within a specific module. ```dart final class HomeModule extends Module { @override List imports() => [SharedModule()]; @override void binds() { i.registerLazySingleton( () => HomeController(i.get()), ); } @override List routes() => [ route('/', child: (_, _) => const HomePage()), ]; } ``` -------------------------------- ### Stack Manipulation with ContextNavigationExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Shows how to manage the navigation stack using `canPop`, `pop`, and `replaceStack` methods from ContextNavigationExtension. ```dart if (context.canPop()) context.pop(); ``` ```dart await context.replaceStack(['/home', '/profile', '/settings']); ``` -------------------------------- ### ContextInjectionExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Provides access to dependencies registered in GetIt via BuildContext. ```APIDOC ## ContextInjectionExtension ### Description Enables retrieval of dependencies from GetIt directly from the BuildContext. ### Methods - **read({param1, param2, type, instanceName})** (T) - Synchronously retrieves a dependency. - **readAsync({param1, param2, type, instanceName})** (Future) - Asynchronously retrieves a dependency. ``` -------------------------------- ### ContextMatchExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Utilities for verifying registered routes, matching locations, and extracting parameters. ```APIDOC ## ContextMatchExtension ### Description Allows checking if paths or route names are registered, finding matching routes, and extracting path parameters. ### Methods - **isKnownPath(path)** (bool) - Checks if the path is registered. - **isKnownRouteName(name)** (bool) - Checks if the route name exists. - **matchingRoute(location)** (GoRoute?) - Returns the corresponding route. - **matchParams(location)** (Map?) - Extracts parameters from the path. - **state** (GoRouterState) - Accesses the current GoRouter state. ``` -------------------------------- ### AfterLayoutMixin Source: https://github.com/bed72/modugo/blob/master/doc/documentation/utilities/index.md A mixin that executes a callback after the first frame of a widget is rendered, providing a valid BuildContext. ```APIDOC ## AfterLayoutMixin ### Description Mixin that executes a callback after the first frame of the widget is rendered. Useful for operations requiring a valid BuildContext such as showing dialogs, triggering initial data loads, or starting animations. ### Behavior - `afterFirstLayout` is called exactly once after the first frame. - Automatically checks `mounted` before execution. - Supports both synchronous and asynchronous operations. ``` -------------------------------- ### Uri Path and Query Parameter Operations in Dart Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Demonstrates how to use methods like `fullPath`, `hasQueryParam`, and `getQueryParam` on a Dart Uri object. Ensure the Uri is parsed correctly before using these methods. ```dart final uri = Uri.parse('/page?foo=1#section'); uri.fullPath; uri.hasQueryParam('foo'); uri.getQueryParam('foo'); ``` -------------------------------- ### Definir StatefulShellModuleRoute Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Cria navegação baseada em abas que preserva o estado e o histórico de cada branch. ```dart StatefulShellModuleRoute( builder: (context, state, shell) => BottomBarWidget(shell: shell), routes: [ ModuleRoute(path: '/', module: HomeModule()), ModuleRoute(path: '/profile', module: ProfileModule()), ModuleRoute(path: '/favorites', module: FavoritesModule()), ], ) ``` -------------------------------- ### Define Routes with Declarative DSL Source: https://github.com/bed72/modugo/blob/master/README.md Use the Module class to define application routes fluently using helpers like child, module, and shell. ```dart final class AppModule extends Module { @override List routes() => [ child(child: (_, _) => const HomePage()), module(module: AuthModule()), alias(from: '/cart/:id', to: '/order/:id'), shell( builder: (_, _, child) => MainShell(child: child), routes: [ child(path: '/dashboard', child: (_, _) => const DashboardPage()), ], ), statefulShell( builder: (_, _, shell) => BottomBarWidget(shell: shell), routes: [ module(module: FeedModule()), module(module: ProfileModule()), ], ), ]; } ``` -------------------------------- ### Implement and Apply Route Guards Source: https://github.com/bed72/modugo/blob/master/README.md Create access control logic by implementing IGuard and apply it to individual routes or propagate it across modules. ```dart final class AuthGuard implements IGuard { @override FutureOr call(BuildContext context, GoRouterState state) async { final isLoggedIn = await checkAuth(); return isLoggedIn ? null : '/login'; } } ``` ```dart // Por rota route('/', child: (_, _) => const HomePage(), guards: [AuthGuard()]); // Propagação para todos os filhos List routes() => propagateGuards( guards: [AuthGuard()], routes: [ module('/home', HomeModule()), module('/profile', ProfileModule()), ], ); ``` -------------------------------- ### Ciclo de Vida do Módulo (initState e dispose) Source: https://github.com/bed72/modugo/blob/master/doc/documentation/modules/index.md Implementação dos métodos de ciclo de vida para inicialização e limpeza de recursos. ```dart final class AnalyticsModule extends Module { @override void initState() { super.initState(); debugPrint('AnalyticsModule inicializado'); } } ``` ```dart final class ChatModule extends Module { @override void dispose() { // Limpar recursos super.dispose(); } } ``` -------------------------------- ### Recuperar dependências via BuildContext Source: https://github.com/bed72/modugo/blob/master/doc/documentation/injection/index.md Utilize extensões de BuildContext para acessar dependências de forma síncrona ou assíncrona. ```dart final controller = context.read(); // Com instância nomeada final primaryDb = context.read(instanceName: 'primary'); ``` ```dart final service = await context.readAsync(); ``` -------------------------------- ### Migração para API Declarativa (v4.x) Source: https://github.com/bed72/modugo/blob/master/doc/documentation/migration/index.md Exemplo de comparação entre a sintaxe antiga (v3) e a nova API declarativa (DSL) da v4.x. ```dart // Ainda funciona (v3 style) ChildRoute(path: '/', child: (_, _) => const HomePage()); ModuleRoute(path: '/auth', module: AuthModule()); // Novo (v4 style) - opcional route('/', child: (_, _) => const HomePage()); module('/auth', AuthModule()); ``` -------------------------------- ### Define Routes with DSL Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md Comparison between traditional route definition and the fluent DSL approach. ```dart List routes() => [ ChildRoute(path: '/', child: (_, _) => const HomePage()), ModuleRoute(path: '/auth', module: AuthModule()), AliasRoute(from: '/cart/:id', to: '/order/:id'), ]; ``` ```dart List routes() => [ route('/', child: (_, _) => const HomePage()), module('/auth', AuthModule()), alias(from: '/cart/:id', to: '/order/:id'), ]; ``` -------------------------------- ### Configure Modugo Source: https://github.com/bed72/modugo/blob/master/doc/index.md Initialize Modugo in the main function before running the app. ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Modugo.configure(module: AppModule(), initialRoute: '/'); runApp(const AppWidget()); } ``` -------------------------------- ### Invoke Context7 in Prompts Source: https://github.com/bed72/modugo/blob/master/doc/documentation/ai/index.md Include the context directive in your AI prompts to ensure the assistant retrieves the correct Modugo API documentation. ```text Como criar um módulo com guard de autenticação? use context7 ``` -------------------------------- ### Implement IGuard Interface Source: https://github.com/bed72/modugo/blob/master/doc/documentation/guards/index.md Define a custom guard by implementing the IGuard interface. Return null to allow access or a String path to redirect. ```dart final class AuthGuard implements IGuard { final AuthRepository _repository; AuthGuard({required AuthRepository repository}) : _repository = repository; @override FutureOr call(BuildContext context, GoRouterState state) async { final isAuthenticated = await _repository.isAuthenticated(); // Retorna null para permitir acesso // Retorna um path para redirecionar return isAuthenticated ? null : '/login'; } } ``` -------------------------------- ### StatefulShellModuleRoute Configuration Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Ideal for tab-based navigation that preserves the state of each tab. Each tab becomes an independent branch with its own route stack, integrating seamlessly with Modugo modules. ```APIDOC ## StatefulShellModuleRoute Ideal for tab-based navigation, preserving the state of each tab. ✅ Benefits: - Each tab has its own navigation stack. - Switching tabs preserves history and state. - Full integration with Modugo modules, including guards and lifecycle. 🎯 Use Cases: - Bottom navigation with independent tabs (Home, Profile, Favorites). - Admin panels or dashboards with persistent navigation. - Apps like Instagram, Twitter, or banking apps with separate stacked flows. 💡 Functionality: Internally, it uses GoRouter's `StatefulShellRoute`. Each `ModuleRoute` becomes an independent branch with its own route stack. ### Example Usage ```dart StatefulShellModuleRoute( builder: (context, state, shell) => BottomBarWidget(shell: shell), routes: [ ModuleRoute(path: '/', module: HomeModule()), ModuleRoute(path: '/profile', module: ProfileModule()), ModuleRoute(path: '/favorites', module: FavoritesModule()), ], ) ``` ``` -------------------------------- ### ModuleRoute Configuration Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Represents an entire module as a route within the navigation structure. ```APIDOC ## ModuleRoute Represents an entire module as a route. ### Example Usage ```dart ModuleRoute( path: '/profile', module: ProfileModule(), ) ``` ``` -------------------------------- ### Extracting Path and Query Parameters with GoRouterStateExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Demonstrates retrieving path parameters and typed query parameters using `getPathParam`, `getIntQueryParam`, `getBoolQueryParam`, and `getStringQueryParam` from GoRouterStateExtension. ```dart final id = state.getPathParam('id'); final page = state.getIntQueryParam('page'); final isActive = state.getBoolQueryParam('active'); final search = state.getStringQueryParam('q'); ``` -------------------------------- ### Route Existence Checks with ContextMatchExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Shows how to verify if a path or route name is known using `isKnownPath` and `isKnownRouteName` from ContextMatchExtension. ```dart final isValid = context.isKnownPath('/settings'); final isNamed = context.isKnownRouteName('profile'); ``` -------------------------------- ### Accessing Modugo Router Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Demonstrates the two ways to access the configured Modugo router: via a global getter or through the Modugo class. ```dart // Via getter global modugoRouter // Via classe Modugo Modugo.routerConfig ``` -------------------------------- ### Estrutura de Diretórios do Projeto Source: https://github.com/bed72/modugo/blob/master/doc/documentation/modules/index.md Representação visual da organização de arquivos em um projeto Flutter modularizado. ```text /lib /modules /home home_page.dart home_module.dart /profile profile_page.dart profile_module.dart /chat chat_page.dart chat_module.dart app_module.dart app_widget.dart main.dart ``` -------------------------------- ### Define ShellModuleRoute Source: https://github.com/bed72/modugo/blob/master/README.md Use ShellModuleRoute to create layouts with shared UI components. ```dart ShellModuleRoute( builder: (context, state, child) => Scaffold(body: child), routes: [ ChildRoute(path: '/user', child: (_, _) => const UserPage()), ChildRoute(path: '/config', child: (_, _) => const ConfigPage()), ], ) ``` -------------------------------- ### Reloading Current Route with ContextNavigationExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Demonstrates how to reload the current route using the `reload` method from ContextNavigationExtension. ```dart context.reload(); ``` -------------------------------- ### CompilerRoute Source: https://github.com/bed72/modugo/blob/master/doc/documentation/utilities/index.md Utility for validating, compiling, and manipulating dynamic route patterns using path_to_regexp. ```APIDOC ## CompilerRoute ### Description Utility for validating, compiling, and manipulating dynamic route patterns. ### Methods - **match(path)** (bool) - Checks if the path matches the pattern. - **extract(path)** (Map?) - Extracts parameters from the path. - **build(args)** (String) - Constructs a concrete path from parameters. - **parameters** (List) - Returns the list of parameter names. - **regExp** (RegExp) - Returns the compiled regular expression. ``` -------------------------------- ### Implement the AppWidget Source: https://github.com/bed72/modugo/blob/master/README.md Use the modugoRouter configuration in the MaterialApp.router. ```dart class AppWidget extends StatelessWidget { const AppWidget({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router(routerConfig: modugoRouter); } } ``` -------------------------------- ### ShellModuleRoute Configuration Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Creates an internal navigation area, similar to Flutter Modular's RouteOutlet, ideal for layouts with menus or tabs where only a portion of the screen changes. Internally uses GoRouter's ShellRoute. ```APIDOC ## ShellModuleRoute Use `ShellModuleRoute` to create an internal navigation area, similar to `RouteOutlet` in Flutter Modular. Ideal for layouts with menus or tabs, where only part of the screen changes. ℹ️ Internally, it utilizes `GoRouter`'s `ShellRoute`. ### Example Usage ```dart final class HomeModule extends Module { @override List routes() => [ ShellModuleRoute( builder: (context, state, child) => PageWidget(child: child), routes: [ ChildRoute(path: '/user', child: (_, _) => const UserPage()), ChildRoute(path: '/config', child: (_, _) => const ConfigPage()), ChildRoute(path: '/orders', child: (_, _) => const OrdersPage()), ], ), ]; } ``` ``` -------------------------------- ### Definir ModuleRoute Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/index.md Representa um módulo inteiro como uma rota. ```dart ModuleRoute( path: '/profile', module: ProfileModule(), ) ``` -------------------------------- ### Logger Source: https://github.com/bed72/modugo/blob/master/doc/documentation/utilities/index.md Internal logging system with ANSI color support and DevTools integration. ```APIDOC ## Logger ### Description Internal logging system for Modugo. Logs are silenced by default unless `debugLogDiagnostics` is enabled in `Modugo.configure`. ### Methods - **Logger.information(msg)** - INFO level (Blue) - **Logger.debug(msg)** - DEBUG level (Green) - **Logger.warn(msg)** - WARN level (Yellow) - **Logger.error(msg)** - ERROR level (Red) - **Logger.module(msg)** - MODULE level (Cyan) - **Logger.injection(msg)** - INJECT level (Green) - **Logger.dispose(msg)** - DISPOSE level (Gray) - **Logger.navigation(msg)** - NAVIGATION level (Cyan) ``` -------------------------------- ### Route Validation with ContextNavigationExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Illustrates checking route existence before navigation using `canPush` from ContextNavigationExtension. ```dart if (context.canPush('/settings')) { context.go('/settings'); } ``` -------------------------------- ### Diagrama de Composição de Módulos Source: https://github.com/bed72/modugo/blob/master/doc/documentation/modules/index.md Representação hierárquica da árvore de dependências e rotas entre módulos. ```text AppModule ├── imports: [CoreModule] ├── binds: AuthService └── routes: ├── HomeModule │ ├── imports: [SharedModule] │ ├── binds: HomeController │ └── routes: ['/'] ├── ChatModule │ ├── binds: ChatService │ └── routes: ['/'] └── ProfileModule ├── imports: [SharedModule] ← já registrado, skip ├── binds: ProfileController └── routes: ['/'] ``` -------------------------------- ### Modugo Configuration Source: https://github.com/bed72/modugo/blob/master/doc/documentation/getting-started/index.md Steps to configure the Modugo framework in your Flutter application. ```APIDOC ## Modugo Configuration ### 1. Create the Root Module (`AppModule`) The root module (`AppModule`) is the entry point for your application. It aggregates all sub-modules, global dependencies, and routes. ```dart final class AppModule extends Module { @override void binds() { i.registerSingleton(AuthService()); } @override List routes() => [ route('/', child: (_, _) => const HomePage()), module('/auth', AuthModule()), module('/profile', ProfileModule()), ]; } ``` ### 2. Configure in `main.dart` Initialize Modugo in your `main` function. ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Modugo.configure( module: AppModule(), initialRoute: '/', ); runApp(const AppWidget()); } ``` ### 3. Create the `AppWidget` Set up your `MaterialApp.router` to use the `modugoRouter`. ```dart class AppWidget extends StatelessWidget { const AppWidget({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( routerConfig: modugoRouter, ); } } ``` ``` -------------------------------- ### Event System Communication Source: https://github.com/bed72/modugo/blob/master/README.md Use the Event bus for decoupled communication between modules and listen to automatic navigation events. ```dart // Definir evento final class UserLoggedInEvent { final String userId; UserLoggedInEvent(this.userId); } // Emitir Event.emit(UserLoggedInEvent('user-123')); // Ouvir Event.i.on((event) { print('Logou: ${event.userId}'); }); ``` ```dart Event.i.on((event) { print('Navegou para: ${event.location}'); }); ``` -------------------------------- ### Define StatefulShellModuleRoute Source: https://github.com/bed72/modugo/blob/master/README.md Use StatefulShellModuleRoute for navigation patterns like bottom navigation bars with multiple stacks. ```dart StatefulShellModuleRoute( builder: (context, state, shell) => BottomBarWidget(shell: shell), routes: [ ModuleRoute(path: '/', module: HomeModule()), ModuleRoute(path: '/profile', module: ProfileModule()), ], ) ``` -------------------------------- ### ShellModuleRoute Definition Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md Groups routes under a shared layout. It takes a builder for the shared layout and a list of child routes. ```APIDOC ## `shell()` — Creates a ShellModuleRoute ### Description Groups routes under a shared layout. ### Method `shell` ### Endpoint N/A (DSL method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart shell( builder: (_, _, child) => AppScaffold(child: child), routes: [ route('/feed', child: (_, _) => const FeedPage()), route('/settings', child: (_, _) => const SettingsPage()), ], observers: [MyObserver()], navigatorKey: shellKey, parentNavigatorKey: parentKey, pageBuilder: (_, _, child) => MaterialPage(child: child), ); ``` ### Response #### Success Response (200) Returns a `ShellModuleRoute` object. #### Response Example N/A (DSL method) ``` -------------------------------- ### StatefulShellModuleRoute Definition Source: https://github.com/bed72/modugo/blob/master/doc/documentation/routes/dsl.md Enables navigation with multiple independent stacks, typically used for tabs or bottom navigation bars. It requires a builder for the navigation UI and a list of child modules. ```APIDOC ## `statefulShell()` — Creates a StatefulShellModuleRoute ### Description Navigation with multiple independent stacks (tabs, bottom navigation). ### Method `statefulShell` ### Endpoint N/A (DSL method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart statefulShell( builder: (_, _, shell) => BottomBarWidget(shell: shell), routes: [ module('/home', HomeModule()), module('/profile', ProfileModule()), ], key: shellKey, parentNavigatorKey: parentKey, ); ``` ### Response #### Success Response (200) Returns a `StatefulShellModuleRoute` object. #### Response Example N/A (DSL method) ``` -------------------------------- ### Uri Extension Methods Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md A collection of methods to extend standard Uri functionality for easier path and query parameter management. ```APIDOC ## Uri Extension Methods ### Description Utility methods to handle Uri path manipulation and query parameter inspection. ### Methods - **fullPath**: Returns the complete path including query and fragment as a String. - **hasQueryParam(key)**: Checks if a specific query parameter exists. Returns a bool. - **getQueryParam(key, {defaultValue})**: Retrieves the value of a query parameter as a String?. - **isSubPathOf(other)**: Checks if the current Uri is a sub-path of another Uri. Returns a bool. - **withAppendedPath(subPath)**: Returns a new Uri with the provided subPath concatenated. Returns a Uri. ### Usage Example ```dart final uri = Uri.parse('/page?foo=1#section'); uri.fullPath; // '/page?foo=1#section' uri.hasQueryParam('foo'); // true uri.getQueryParam('foo'); // '1' final base = Uri.parse('/api'); uri.isSubPathOf(base); // false final extended = base.withAppendedPath('users'); // → Uri('/api/users') ``` ``` -------------------------------- ### Accessing Navigation Extras and State with GoRouterStateExtension Source: https://github.com/bed72/modugo/blob/master/doc/documentation/extensions/index.md Shows how to access navigation extras with type casting using `getExtra` and `argumentsOrThrow`, and check initial route status with `isInitialRoute` from GoRouterStateExtension. ```dart final data = state.getExtra(); final required = state.argumentsOrThrow(); // throws se null ``` ```dart if (state.isInitialRoute) { // Estamos na raiz } ```