### Installing Dependencies (npm/yarn) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/development.md Install the necessary project dependencies using either the npm or yarn package manager. This command should be executed in the directory containing the package.json file. ```npm $ npm install ``` ```yarn $ yarn install ``` -------------------------------- ### Create New Stacked Flutter App using CLI Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/00-overview.md This command utilizes the Stacked CLI (`stacked`) to generate a new Flutter application project named `my_first_app`. It sets up the default Stacked architecture, state management, navigation, and other components as a starting point. Requires the Stacked CLI to be installed and Flutter SDK to be set up. ```shell stacked create app my_first_app ``` -------------------------------- ### Install Stacked CLI using Dart Pub Global Activate Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/00-overview.md This command uses the Dart package manager (`pub`) to activate the `stacked_cli` package globally. Activating it globally makes the `stacked` command available system-wide for generating and managing Stacked projects. Prerequisites include having the Dart SDK installed and configured. ```shell dart pub global activate stacked_cli ``` -------------------------------- ### Navigating to CounterView (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/01-how-it-works.md Illustrates how to update the navigation logic in `startup_viewmodel.dart` to replace the current view with the newly created `CounterView`. This directs the application's initial route to the counter example screen. ```dart _navigationService.replaceWithCounterView(); ``` -------------------------------- ### Original Navigation Call Example (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/01-how-it-works.md This snippet shows a placeholder or previous navigation call in `startup_viewmodel.dart`, which is presented as context before demonstrating how to change the initial navigation route to the new counter view. ```dart _navigationService.replaceWithHomeView(); ``` -------------------------------- ### Installing Stacked CLI | Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md This command globally activates the `stacked_cli` package using Dart's package manager. It makes the `stacked` command available system-wide for use in your terminal. ```shell dart pub global activate stacked_cli ``` -------------------------------- ### Starting Docusaurus Locally with Specific Locale (Bash) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/translation.md This Bash command starts the Docusaurus development server using a specific locale. Replace `{locale}` with the desired locale code (e.g., 'es') to preview the translated site. ```bash npm run start -- --locale es ``` -------------------------------- ### Configuring Stacked App Logger - Stacked - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/logger.md Enables the built-in Stacked logger by providing the `StackedLogger` instance to the `@StackedApp` annotation. This annotation is applied to the main application setup class. ```Dart @StackedApp( logger: StackedLogger(), ) ``` -------------------------------- ### Running Development Server (npm/yarn) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/development.md Start a local development server to preview changes while editing files. This server typically watches for file modifications and automatically reloads the site in a browser window, usually accessible at http://localhost:3000. ```npm $ npm run start ``` ```yarn $ yarn start ``` -------------------------------- ### Configuring Stacked CLI Paths and Settings - JSON Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/es/docusaurus-plugin-content-docs/current/tooling/stacked-cli.md This JSON snippet defines the configuration for the Stacked command-line interface tool. It specifies paths to core application directories like app files, services, views, bottom sheets, and dialogs, along with test-specific paths and settings like the locator name, mock registration function, preferred Stacked view version (v1 or v2), and code line length for formatting. ```json { "stacked_app_file_path" : "app/app.dart", "services_path" : "services", "views_path" : "ui/views", "bottom_sheets_path": "ui/bottom_sheets", "dialogs_path": "ui/dialogs", "test_helpers_file_path" : "helpers/test_helpers.dart", "test_services_path" : "services", "test_views_path" : "viewmodels", "locator_name" : "locator", "register_mocks_function" : "registerServices", "v1": false, // Indica si desea utilizar ViewModelBuilder (v1) o el nuevo StackedView (v2) "line_length": 80 // Pasado al formateador Flutter al ejecutar comandos CLI } ``` -------------------------------- ### Example Docusaurus Theme Translation (JSON) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/translation.md This JSON snippet shows an example of a theme-specific translation file, such as `navbar.json` for the classic theme. It contains keys and messages for text labels used within the theme. ```json { "title": { "message": "My Site", "description": "The title in the navbar" }, "item.label.Docs": { "message": "Docs", "description": "Navbar item with label Docs" }, "item.label.Blog": { "message": "Blog", "description": "Navbar item with label Blog" }, "item.label.GitHub": { "message": "GitHub", "description": "Navbar item with label GitHub" } } ``` -------------------------------- ### Defining Stacked View with Required Arguments (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Shows a Stacked view (`HomeView`) defined with a required constructor parameter (`startingIndex`). This setup requires that the argument be provided when navigating to this view, and the Stacked code generator will include this requirement in the generated navigation helper. ```Dart class HomeView extends StackedView { final int startingIndex; const HomeView({Key? key, required this.startingIndex}) : super(key: key); ... } ``` -------------------------------- ### Generating Stacked Service via CLI - Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/fr/docusaurus-plugin-content-docs/current/in-depth/services.md This shell command demonstrates how to use the Stacked CLI to automatically generate a new service class named 'api'. It handles boilerplate setup, including creating the service file, registering it with the service locator, and setting up unit test mocks. ```Shell stacked create service api ``` -------------------------------- ### Example Docusaurus React Code Translation (JSON) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/translation.md This JSON snippet provides an example of the `i18n/{locale}/code.json` file structure. This file contains translation keys and messages extracted from your React components, often including descriptions for context. ```json { "Welcome to my website": { "message": "Welcome to my website" }, "home.visitMyBlog": { "message": "You can also visit my {blog}", "description": "The homepage message to ask the user to visit my blog" }, "homepage.visitMyBlog.linkLabel": { "message": "Blog", "description": "The label for the link to my blog" }, "Home icon": { "message": "Home icon", "description": "The homepage icon alt message" } } ``` -------------------------------- ### Adding New Stacked Service | Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md Run this command in your project's root directory to generate a new Service class. It places the service file in the designated services folder and registers it as a dependency in the application's setup file (`app.dart`). ```shell stacked create service stripe ``` -------------------------------- ### Adding Logger Dependency - pubspec.yaml - YAML Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/logger.md Includes the necessary `logger` package in the project's dependencies list within the `pubspec.yaml` file. This step is required to make the logger functionality available. ```YAML dependencies: ... logger: ``` -------------------------------- ### Creating Stacked View | Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/04-form-basics.md Command line instruction to generate a new Stacked View named `textReverse`. This command sets up the initial view and ViewModel files for the application feature, requiring the Stacked CLI to be installed and configured. ```shell stacked create view textReverse ``` -------------------------------- ### Using Generated Logger Instance - Stacked - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/logger.md Demonstrates how to obtain a logger instance specific to a class using the generated `getLogger` function and log an informational message. It automatically includes the function name where the log is called. ```Dart class MyViewModel { final logger = getLogger('MyViewModel'); void doStuff() { logger.i(''); } } ``` -------------------------------- ### Creating Custom Route Transition Builder Function (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Provides an example of a static method within a class (`CustomRouteTransition`) that serves as a custom transition builder function. It shows the required signature (`Widget Function(BuildContext, Animation, Animation, Widget)`) and how to use existing Flutter transition widgets (like `SharedAxisTransition` from the `animations` package) within it. ```Dart import 'package:animations/animations.dart'; import 'package:flutter/material.dart'; class CustomRouteTransition { static Widget sharedAxis(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { // Here you can use any Existing Transition class in Flutter return SharedAxisTransition( animation: animation, secondaryAnimation: secondaryAnimation, transitionType: SharedAxisTransitionType.scaled, child: child, ); } } ``` -------------------------------- ### Implementing StreamViewModel, View, and Service - Stacked Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Provides a complete example demonstrating how to create a StreamViewModel that subscribes to data from a service stream. It includes the ViewModel, the corresponding View using ViewModelBuilder to reactively update based on stream data, and a simple service simulating epoch time updates. ```Dart // ViewModel class StreamCounterViewModel extends StreamViewModel { String get title => 'This is the time since epoch in seconds \n $data'; @override Stream get stream => locator().epochUpdatesNumbers(); } // View class StreamCounterView extends StatelessWidget { @override Widget build(BuildContext context) { return ViewModelBuilder.reactive( builder: (context, viewModel, child) => Scaffold( body: Center( child: Text(viewModel.title), ), ), viewModelBuilder: () => StreamCounterViewModel(), ); } } // Service (registered using injectable, NOT REQUIRED) @lazySingleton class EpochService { Stream epochUpdatesNumbers() async* { while (true) { await Future.delayed(const Duration(seconds: 2)); yield DateTime.now().millisecondsSinceEpoch; } } } ``` -------------------------------- ### Customizing Logger Helper Name - Stacked - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/logger.md Configures the `StackedLogger` to use a custom name for the generated logger retrieval function (e.g., `getStackedLogger`) instead of the default `getLogger`. This is useful if `getLogger` is already defined elsewhere. ```Dart @StackedApp( logger: StackedLogger( logHelperName: 'getStackedLogger', ) ) ``` -------------------------------- ### Marking Service Registration in Stacked App (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md Place this comment identifier in your `lib/app/app.dart` file, typically below the last service registration within your Stacked setup, so the Stacked CLI can automatically register new services created via the CLI. ```dart // @stacked-service ``` -------------------------------- ### Enabling Flutter Navigator V2 in Stacked Generator YAML Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/stacked-router/01-routing-basics.md This YAML configuration snippet for build.yaml instructs the build_runner how to configure the stackedRouterGenerator. By setting navigator2: true under the generator options, it ensures that the generated routing code is compatible with Flutter's V2 navigator, a requirement for using the RouterService effectively for web navigation. This relies on the build_runner and stacked_generator packages. ```YAML targets: $default: builders: stacked_generator|stackedRouterGenerator: options: navigator2: true ``` -------------------------------- ### Minimal StreamViewModel Definition - Stacked Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Shows the minimal code required to define a StreamViewModel. It extends the base class and overrides the mandatory 'stream' getter to provide the stream the ViewModel should listen to, highlighting the simplicity of setup. ```Dart class StreamCounterViewModel extends StreamViewModel { @override Stream get stream => locator().epochUpdatesNumbers(); } ``` -------------------------------- ### Implementing MultipleStreamViewModel in Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Demonstrates how to extend `MultipleStreamViewModel` to manage multiple data streams. It shows how to override the `streamsMap` getter to associate string keys with `StreamData` objects and includes examples of async generator functions creating streams that emit numbers and strings with delays. ```Dart const String _NumbersStreamKey = 'numbers-stream'; const String _StringStreamKey = 'string-stream'; class MultipleStreamsExampleViewModel extends MultipleStreamViewModel { int numbersStreamDelay = 500; int stringStreamDelay = 2000; @override Map get streamsMap => { _NumbersStreamKey: StreamData(numbersStream(numbersStreamDelay)), _StringStreamKey: StreamData(stringStream(stringStreamDelay)), }; Stream numbersStream([int delay = 500]) async* { var random = Random(); while (true) { await Future.delayed(Duration(milliseconds: delay)); yield random.nextInt(999); } } Stream stringStream([int delay = 2000]) async* { var random = Random(); while (true) { await Future.delayed(Duration(milliseconds: delay)); var randomLength = random.nextInt(50); var randomString = ''; for (var i = 0; i < randomLength; i++) { randomString += String.fromCharCode(random.nextInt(50)); } yield randomString; } } } ``` -------------------------------- ### Configuring Stacked App with RouterService Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/stacked-router/01-routing-basics.md This Dart snippet shows how to configure the Stacked application using the @StackedApp annotation. It registers the RouterService as a lazy singleton dependency, replacing the older NavigationService to enable support for Flutter's V2 navigator, which is better suited for web URL handling. This requires the stacked_generator dependency. ```Dart @StackedApp( routes: [ ... ], dependencies: [ LazySingleton(classType: RouterService), LazySingleton(classType: DialogService), LazySingleton(classType: BottomSheetService), ] ) class App {} ``` -------------------------------- ### Implementing MultipleFutureViewModel - Stacked Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Defines a MultipleFutureViewModel to manage and execute multiple futures concurrently. It uses the 'futuresMap' getter to specify the futures to run, identified by string keys, and provides examples of accessing fetched data and individual busy states. ```Dart import 'package:stacked/stacked.dart'; const String _NumberDelayFuture = 'delayedNumber'; const String _StringDelayFuture = 'delayedString'; class MultipleFuturesExampleViewModel extends MultipleFutureViewModel { int get fetchedNumber => dataMap[_NumberDelayFuture]; String get fetchedString => dataMap[_StringDelayFuture]; bool get fetchingNumber => busy(_NumberDelayFuture); bool get fetchingString => busy(_StringDelayFuture); @override Map get futuresMap => { _NumberDelayFuture: getNumberAfterDelay, _StringDelayFuture: getStringAfterDelay, }; Future getNumberAfterDelay() async { await Future.delayed(Duration(seconds: 2)); return 3; } Future getStringAfterDelay() async { await Future.delayed(Duration(seconds: 3)); return 'String data'; } } ``` -------------------------------- ### Implementing FutureViewModel with Error Handling - Stacked Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Extends the FutureViewModel example to include error handling. It shows how to override the 'onError' callback to perform actions when an error occurs during future execution and demonstrates throwing an exception within the future function. ```Dart class FutureExampleViewModel extends FutureViewModel { @override Future get future => getDataFromServer(); Future getDataFromServer() async { await Future.delayed(const Duration(seconds: 3)); throw Exception('This is an error'); } @override void onError(error) { } } ``` -------------------------------- ### Building Static Site (npm/yarn) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/development.md Build the Docusaurus website into a directory of static content. The generated files will be placed in the '/build' directory, ready to be deployed to a static file hosting service. ```npm $ npm run build ``` ```yarn $ yarn build ``` -------------------------------- ### Implementing Startup Navigation Logic in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/02-startup-logic.md This Dart code snippet in the `StartupViewModel` contains the core application startup logic. It retrieves the `AuthenticationService` and `NavigationService` via the `locator`. The `runStartupLogic` method checks the simulated login status using the `authenticationService` and uses the `navigationService` to conditionally navigate to `HomeView` if logged in or `LoginView` otherwise, replacing the current view. ```dart class StartupViewModel extends BaseViewModel { // 1. Get the Authentication and NavigationService final _authenticationService = locator(); final _navigationService = locator(); Future runStartupLogic() async { // 2. Check if the user is logged in if (_authenticationService.userLoggedIn()) { // 3. Navigate to HomeView _navigationService.replaceWith(Routes.homeView); } else { // 4. Or navigate to LoginView _navigationService.replaceWith(Routes.loginView); } } } ``` -------------------------------- ### Creating Authentication Service with Stacked CLI Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/02-startup-logic.md This shell command utilizes the Stacked CLI to create a new service named 'authentication'. This command generates the `authentication_service.dart` file and automatically registers the service for dependency injection within the Stacked architecture. ```shell stacked create service authentication ``` -------------------------------- ### Creating Login View with Stacked CLI Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/02-startup-logic.md This shell command uses the Stacked CLI to generate the boilerplate code for a new view named 'login'. This includes creating the `login_view.dart` and `login_viewmodel.dart` files. ```shell stacked create view login ``` -------------------------------- ### Navigating Back in Stacked Using NavigationService (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Demonstrates how to pop the current view off the navigation stack and return to the previous view using the basic `back()` method of the `NavigationService`. This is equivalent to the user pressing the system back button. ```Dart _navigationService.back(); ``` -------------------------------- ### Run Stacked Flutter App using Flutter Command Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/00-overview.md After creating the Stacked project using the CLI, this standard Flutter command compiles and launches the application on a connected device or emulator. It is used to test and view the generated default Stacked app's initial state and UI. Requires a Flutter project directory and a connected device/emulator. ```shell flutter run ``` -------------------------------- ### Implementing an App Service for Business Logic - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/fr/docusaurus-plugin-content-docs/current/in-depth/services.md This snippet illustrates an App Service (ArtistService) that orchestrates calls to multiple Facade Services (DatabaseService, AuthenticationService, ApiService). It demonstrates implementing business logic, such as checking user login status before fetching and saving data, centralizing complex workflows. ```Dart class ArtistService { final _databaseService = locator(); final _authenticationService = locator(); final _apiService = locator(); Future> getArtists() async { // Vérifier si l'utilisateur est connecté if (_authenticationService.userLoggedIn()) { // Récupérer les artistes depuis le backend final newArtists = await _apiService.getArtists(); // Sauver en base de données await _databaseService.saveArtists(newArtists); return newArtists; } throw Exception('User must be logged in to see artists'); } } ``` -------------------------------- ### Navigating with Required Arguments in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Demonstrates how to navigate to a view (`HomeView`) that requires arguments by passing the necessary parameters (e.g., `startingIndex: 0`) to the generated `navigateTo[ViewName]` method. The generated method's signature reflects the required parameters of the view's constructor. ```Dart _navigationService.navigateToHomeView(startingIndex: 0); ``` -------------------------------- ### Implementing Simulated Authentication Service (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/02-startup-logic.md This Dart code defines a simple `AuthenticationService` class with a `userLoggedIn` method. For demonstration purposes, this method currently returns a static boolean value (`true`), simulating a user's login status without actual authentication logic. This service is intended to be used by ViewModels. ```dart class AuthenticationService { bool userLoggedIn() { return true; } } ``` -------------------------------- ### Creating New Stacked App | Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md Use this command to initialize a new Flutter project pre-configured with the Stacked framework. It sets up the basic directory structure, adds required dependencies, and generates initial Stacked-specific code. ```shell stacked create app my_app ``` -------------------------------- ### Defining Routes in Stacked App Configuration (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Demonstrates how views are registered as routes within the `@StackedApp` annotation in `lib/app/app.dart`. Uses `MaterialRoute` (or `CustomRoute`) to define views and their associated page classes. This configuration is processed by the Stacked code generator to create navigation helper methods. ```Dart @StackedApp(routes: [ MaterialRoute(page: StartupView), MaterialRoute(page: HomeView), MaterialRoute(page: CounterView), // @stacked-route ]) class App {} ``` -------------------------------- ### Navigating to View with Stacked NavigationService (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Explains how to push a new view onto the navigation stack using the generated `navigateTo[ViewName]` helper method from the `NavigationService`. This is the most common navigation type, adding the new view on top of the current one. ```Dart _navigationService.navigateToHomeView(); ``` -------------------------------- ### Creating Stacked View and ViewModel (Shell) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/01-how-it-works.md This command uses the Stacked CLI to automatically generate the necessary files (View, ViewModel, and test) for a new feature or screen named 'counter' within your Stacked application structure. ```shell stacked create view counter ``` -------------------------------- ### Running Stacked Code Generator | Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/04-form-basics.md Command line instruction to execute the Stacked code generator. This command processes annotations like `@FormView` and generates the necessary form-specific code, including controller management and synchronization logic, into a new `.form.dart` file. It requires the Stacked CLI. ```shell stacked generate ``` -------------------------------- ### Generating Stacked Service - Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/services.md Uses the Stacked command-line interface (CLI) to quickly generate the boilerplate code for a new service named 'api'. This command sets up the service class file, a corresponding mock for testing, and registers it with the service locator. ```shell stacked create service api ``` -------------------------------- ### Implementing a Facade Service for API Calls - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/fr/docusaurus-plugin-content-docs/current/in-depth/services.md This snippet defines an ApiService class acting as a Facade Service. It encapsulates the logic for fetching a list of artists, including making the HTTP request, handling the response, decoding JSON, and deserializing data into Artist objects. It throws an exception on failure. ```Dart class ApiService { Future> getArtists() async { final response = await http.get(Uri.https('venu.is', '/artists')); if (response.statusCode < 400) { final responseBodyAsMap = jsonDecode(response.body); final artistMaps = responseBodyAsMap['data'] as List>; return artistMaps.map(Artist.fromJson).toList(); } throw Exception('Response Code: ${response.statusCode} - ${response.body}'); } } ``` -------------------------------- ### Clearing Navigation Stack and Showing View in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Shows how to use the `clearStackAndShow` method to remove all existing views from the navigation stack and then push the specified view (e.g., `Routes.homeView`) onto the now empty stack. This is useful for scenarios like logout or returning to a root screen. ```Dart _navigationService.clearStackAndShow(Routes.homeView); ``` -------------------------------- ### Passing Result Back with Stacked Back Navigation (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Demonstrates how to pass data back to the view that initiated the navigation by providing a value to the `result` parameter of the `back()` method. The result can be of any type (`dynamic`) and is received by the `await` call on the original navigation method. ```Dart _navigationService.back(result: 'From back call'); ``` -------------------------------- ### Replacing View with NavigationService in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Shows how to replace the current view on the navigation stack with a new view using the `replaceWith` method of the `NavigationService`. Requires an instance of `NavigationService` and the generated route name (e.g., `Routes.homeView`). This is often used for initial navigation after startup or resetting flows. ```Dart _navigationService.replaceWith(Routes.homeView); ``` -------------------------------- ### Receiving Navigation Results in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Shows how to await a navigation call (like `replaceWithHomeView`) which returns a `Future`. This allows the calling code to receive a result that is passed back from the navigated view when it is subsequently popped using the `back` method with a `result` parameter. ```Dart final result = await _navigationService.replaceWithHomeView(startingIndex: 0); print('Returned result: $result'); ``` -------------------------------- ### Implementing ReactiveViewModel and Listenable Services (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Explains how to create a ViewModel that automatically reacts to changes in dependent services by extending ReactiveViewModel and implementing the listenableServices getter with a list of services that mix in ListenableServiceMixin. ```Dart class AnyViewModel extends ReactiveViewModel { final _postsService = locator(); int get postCount => _postsService.postCount; @override List get listenableServices => [_postsService]; } ``` -------------------------------- ### Customizing LoginView UI in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/02-startup-logic.md This Dart code snippet shows how to modify the generated `LoginView` widget to set its background color to red. It extends `StackedView` and overrides the `builder` method to return a `Scaffold` with a red background, used here as a visual indicator. ```dart class LoginView extends StackedView { const LoginView({Key? key}) : super(key: key); @override Widget builder( BuildContext context, LoginViewModel viewModel, Widget? child, ) { return Scaffold( backgroundColor: Colors.red, body: Container( padding: const EdgeInsets.only(left: 25.0, right: 25.0), ), ); } @override LoginViewModel viewModelBuilder( BuildContext context, ) => LoginViewModel(); } ``` -------------------------------- ### Replacing View with Arguments in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Shows how to replace the current view on the navigation stack with a new view that requires arguments, passing the arguments (e.g., `startingIndex: 0`) to the generated `replaceWith[ViewName]` method. This combines the replace action with passing data to the new view. ```Dart _navigationService.replaceWithHomeView(startingIndex: 0); ``` -------------------------------- ### Using Custom Transition Builder During Navigation (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Shows how to use a custom static transition builder function (e.g., `CustomRouteTransition.sharedAxis`) by providing it to the `transition` parameter of the `navigateTo` method during a specific navigation call. This applies your custom transition for this particular navigation instance. Requires the target route to be a `CustomRoute`. ```Dart // When navigating await _navigationService.navigateTo( Routes.secondView, transition: transitionsBuilder: CustomRouteTransition.sharedAxis, ); ``` -------------------------------- ### Registering Dependencies with StackedApp Annotation (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/es/docusaurus-plugin-content-docs/current/in-depth/service-locator.md This snippet demonstrates the primary method for registering services with the Stacked Service Locator using the `@StackedApp` annotation. It shows how to define various dependency types like Singleton, LazySingleton, InitializableSingleton, and Factory within the `dependencies` list, illustrating common use cases such as registering navigation, theme, authentication, and shared preferences services, some with abstract type mapping or custom resolution. ```Dart @StackedApp( dependencies: [ Singleton(classType: NavigationService), LazySingleton(classType: ThemeService, resolveUsing: ThemeService.getInstance), LazySingleton(classType: FirebaseAuthService, asType: AuthService), InitializableSingleton(classType: SharedPreferencesService), Factory(classType: FactoryService), ], ) ``` -------------------------------- ### Customizing HomeView UI in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/02-startup-logic.md This Dart code snippet modifies the generated `HomeView` widget to set its background color to purple. Similar to `LoginView`, it overrides the `builder` method to return a `Scaffold` with a purple background, serving as a visual indicator for this screen. ```dart class HomeView extends StackedView { const HomeView({Key? key}) : super(key: key); @override Widget builder( BuildContext context, HomeViewModel viewModel, Widget? child, ) { return Scaffold( backgroundColor: Colors.purple, body: Container( padding: const EdgeInsets.only(left: 25.0, right: 25.0), ), ); } @override HomeViewModel viewModelBuilder( BuildContext context, ) => HomeViewModel(); } ``` -------------------------------- ### Implementing BaseViewModel Methods (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Demonstrates the basic usage of Stacked's BaseViewModel, including setting busy state for the model itself (setBusy) and for a specific object (setBusyForObject), and using runBusyFuture to automatically manage busy state around an asynchronous operation. ```Dart class WidgetOneViewModel extends BaseViewModel { Human _currentHuman; Human get currentHuman => _currentHuman; void setBusyOnProperty() { setBusyForObject(_currentHuman, true); // Fetch updated human data setBusyForObject(_currentHuman, false); } void setModelBusy() { setBusy(true); // Do things here setBusy(false); } Future longUpdateStuff() async { // Sets busy to true before starting future and sets it to false after executing // You can also pass in an object as the busy object. Otherwise it'll use the ViewModel var result = await runBusyFuture(updateStuff()); } Future updateStuff() { return Future.delayed(const Duration(seconds: 3)); } } ``` -------------------------------- ### Defining Stacked View Class Structure (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/01-how-it-works.md Illustrates the basic structure of a View in the Stacked framework. Instead of extending StatelessWidget or StatefulWidget, it extends `StackedView`, where T is the associated ViewModel type, and requires implementing the `builder` and `viewModelBuilder` methods. ```dart class CounterView extends StackedView { @override // A builder function that gives us a ViewModel Widget builder( BuildContext context, CounterViewModel viewModel, Widget? child, ) { return Scaffold( ... ); } @override CounterViewModel viewModelBuilder(BuildContext context) => CounterViewModel(); } ``` -------------------------------- ### Conditionally Registering LazySingleton by Environment (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/es/docusaurus-plugin-content-docs/current/in-depth/service-locator.md This snippet illustrates how to make a dependency registration environment-specific using the `environments` parameter within a dependency type like `LazySingleton`. By specifying `environments: {Environment.dev}`, the `NavigationService` will only be registered by the Service Locator if the `setupLocator` function is called with `environment: Environment.dev`, allowing for flexible environment-based dependency injection configurations. ```Dart LazySingleton( classType: NavigationService, environments: {Environment.dev}, ), ``` -------------------------------- ### Registering Dependencies with StackedApp Annotation (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/service-locator.md Demonstrates how to register different types of services (Singleton, LazySingleton, InitializableSingleton, Factory) using the `dependencies` property of the `@StackedApp` annotation in the Stacked framework. Each entry specifies the concrete class (`classType`) and optionally the interface (`asType`) or a custom resolver (`resolveUsing`). ```dart @StackedApp( dependencies: [ Singleton(classType: NavigationService), LazySingleton(classType: ThemeService, resolveUsing: ThemeService.getInstance), LazySingleton(classType: FirebaseAuthService, asType: AuthService), InitializableSingleton(classType: SharedPreferencesService), Factory(classType: FactoryService), ], ) ``` -------------------------------- ### Creating a Listenable Service with Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Details how to make a service reactive by mixing in ListenableServiceMixin, calling listenToReactiveValues to register reactive properties, and calling notifyListeners() when those properties change to trigger updates in listening ViewModels. ```Dart class PostService with ListenableServiceMixin { PostService() { listenToReactiveValues([_postCount]); } int _postCount = 0; int get postCount => _postCount; Future increment() async { _postCount++; notifyListeners(); // ViewModels listening postCount value are notified and their View is rebuild } } ``` -------------------------------- ### Implementing App Service (Orchestration) - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/services.md Defines an `ArtistService` acting as an App Service. It demonstrates how an App Service orchestrates business logic by utilizing multiple Facade Services (AuthenticationService, ApiService, DatabaseService) via the service locator to perform a sequence of operations like checking login status, fetching data, and saving it. ```dart class ArtistService { final _databaseService = locator(); final _authenticationService = locator(); final _apiService = locator(); Future> getArtists() async { // Check if user is logged in if (_authenticationService.userLoggedIn()) { // Get the artists from the backend final newArtists = await _apiService.getArtists(); // Save to the database await _databaseService.saveArtists(newArtists); return newArtists; } throw Exception('User must be logged in to see artists'); } } ``` -------------------------------- ### Adding New Stacked View | Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md Execute this command from the root of your Stacked project to generate a new View component. It creates the View file, its corresponding ViewModel, a test file, and updates the application's routing configuration. ```shell stacked create view login ``` -------------------------------- ### Applying Custom Transition During Navigation Call (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Demonstrates how to apply a custom transition (e.g., `TransitionsBuilders.fadeIn`) by providing the `transition` parameter directly to the `navigateTo` method. This overrides any default transition set in `app.dart` for that specific navigation. Requires the target route to be configured as a `CustomRoute` in `app.dart`. ```Dart await _navigationService.navigateTo( Routes.secondView, transition: TransitionsBuilders.fadeIn, ); ``` -------------------------------- ### Using Facade Service in ViewModel - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/services.md Shows the refactored `HomeViewModel` that now uses the `ApiService` via the Stacked service locator. The ViewModel's responsibility is reduced to calling the service and handling the returned data, illustrating improved separation of concerns and readability. ```dart class HomeViewModel extends BaseViewModel { final _apiService = locator(); List _artists = []; Future fetchArtists() async { _artists = await _apiService.getArtists(); // Do some stuff with artists or extract additional state e.g. // empty state, multi select, etc ... } } ``` -------------------------------- ### Using Custom Transition Builder in Stacked App (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Demonstrates how to reference a custom static transition builder function (e.g., `CustomRouteTransition.sharedAxis`) in the `transitionsBuilder` property of a `CustomRoute` within the `@StackedApp` configuration in `app.dart`. This applies your custom transition as the default for the specified route. ```Dart // In app.dart CustomRoute( page: CounterView, transitionsBuilder: CustomRouteTransition.sharedAxis, ), ``` -------------------------------- ### Using Facade Service in Stacked ViewModel - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/fr/docusaurus-plugin-content-docs/current/in-depth/services.md This snippet shows how a ViewModel uses a Facade Service (ApiService) to perform data fetching. It locates the service via the locator and delegates the actual work (`_apiService.getArtists()`) to it. This separates concerns, keeping the ViewModel focused on state management. ```Dart class HomeViewModel extends BaseViewModel { final _apiService = locator(); List _artists = []; Future fetchArtists() async { _artists = await _apiService.getArtists(); // Utilisez artistes ou extrayez un état supplémentaire, par ex. // empty state, multi select, etc ... } } ``` -------------------------------- ### Creating Widget using Stacked CLI (Shell) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md Execute this command from the root directory of your Stacked Flutter application to generate a new widget, its associated widget model, and the corresponding test file in the default project structure. ```shell stacked create widget users_list ``` -------------------------------- ### Configuring Custom Route in Stacked App (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Demonstrates how to define a route using `CustomRoute` instead of `MaterialRoute` or `CupertinoRoute` in the `@StackedApp` annotation in `app.dart`. Using `CustomRoute` is required to apply custom transition animations when navigating to the associated view. ```Dart @StackedApp(routes: [ ... CustomRoute(page: CounterView), // <== Custom Route // @stacked-route ]) class App {} ``` -------------------------------- ### Applying Custom Transition at App Level in Stacked (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/03-navigation-basics.md Shows how to specify a custom transition builder (e.g., `TransitionsBuilders.fadeIn` from Stacked's built-in options) for a `CustomRoute` in the `@StackedApp` configuration in `app.dart`. This sets a default custom transition that will be used whenever navigating to this view. ```Dart @StackedApp(routes: [ ... CustomRoute( page: CounterView, transitionsBuilder: TransitionsBuilders.fadeIn, ), // @stacked-route ]) class App {} ``` -------------------------------- ### Copying Docusaurus Doc Files for Translation (Bash) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/translation.md These Bash commands create the necessary directory structure for translated documentation files for a specific locale (`{locale}`) and copy the original Markdown files from the `docs/` directory into this new location for translation. ```bash mkdir -p i18n/{locale}/docusaurus-plugin-content-docs/current cp -r docs/** i18n/{locale}/docusaurus-plugin-content-docs/current ``` -------------------------------- ### Handling Errors from runBusyFuture with Key (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Shows how exceptions caught by runBusyFuture are associated with the provided busyObject key, allowing access to the specific error using error(key) and checking for its presence with hasErrorForKey(key). The constant for the key is also included. ```Dart const String BusyObjectKey = 'my-busy-key'; class BusyExampleViewModel extends BaseViewModel { Future longUpdateStuff() async { // Sets busy to true before starting future and sets it to false after executing // You can also pass in an object as the busy object. Otherwise it'll use the ViewModel var result = await runBusyFuture(updateStuff(), busyObject: BusyObjectKey); } Future updateStuff() { return Future.delayed(const Duration(seconds: 3)); } } ``` -------------------------------- ### Fetching Data Directly in Stacked ViewModel - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/i18n/fr/docusaurus-plugin-content-docs/current/in-depth/services.md This snippet shows an anti-pattern where a ViewModel directly handles HTTP requests, response validation, JSON decoding, and data deserialization. It demonstrates tightly coupling the ViewModel to external dependencies like the http package, making it harder to test and violating the single responsibility principle. ```Dart class HomeViewModel extends BaseViewModel { List _artists = []; Future fetchArtists() async { // #1: Structure la requête http final response = await http.get(Uri.https('venu.is', '/artists')); // #2: Valide si la réponse est un succès if (response.statusCode < 400) { // #3: Convertit la réponse en map final responseBodyAsMap = jsonDecode(response.body); // #4: Récupère les informations utiles de la réponse final artistMaps = responseBodyAsMap['data'] as List>; // #5: Désérialise en une liste d'artistes _artists = artistMaps.map(Artist.fromJson).toList(); } } } class Artist { final String name; final String coverImage; Artist({required this.name, required this.coverImage}); factory Artist.fromJson(Map data) => Artist( name: data['name'], coverImage: data['coverImage'], ); } ``` -------------------------------- ### Implementing Facade Service (Data Fetching) - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/services.md Defines an `ApiService` class that acts as a Facade Service. It encapsulates the HTTP request logic, success validation, and JSON deserialization previously handled by the ViewModel, returning a clean `List` or throwing an exception on failure. This separates external dependency handling from the ViewModel. ```dart class ApiService { Future> getArtists() async { final response = await http.get(Uri.https('venu.is', '/artists')); if (response.statusCode < 400) { final responseBodyAsMap = jsonDecode(response.body); final artistMaps = responseBodyAsMap['data'] as List>; return artistMaps.map(Artist.fromJson).toList(); } throw Exception('Response Code: ${response.statusCode} - ${response.body}'); } } ``` -------------------------------- ### Syncing IndexTrackingViewModel with Web Routes (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Demonstrates how to initialize the `IndexTrackingViewModel`'s index based on the current web route using the `setCurrentWebPageIndex` method. This is useful for maintaining the correct index state when a user refreshes a web page. ```Dart class BottomNavExampleViewModel extends IndexTrackingViewModel { final _routerService = exampleLocator(); BottomNavExampleViewModel() { setCurrentWebPageIndex(_routerService); } } ``` -------------------------------- ### Default Stacked CLI Configuration (JSON) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md This JSON structure shows the default values for paths and settings used by the Stacked CLI. You can override any of these defaults by creating a `stacked.json` file in your project root and including the properties you wish to customize. ```json { "bottom_sheets_path": "ui/bottom_sheets", "dialogs_path": "ui/dialogs", "line_length": 80, "locator_name": "locator", "prefer_web": true, "register_mocks_function": "registerServices", "services_path": "services", "stacked_app_file_path": "app/app.dart", "test_helpers_file_path": "helpers/test_helpers.dart", "test_services_path": "services", "test_views_path": "viewmodels", "test_widgets_path": "widget_models", "v1": false, "views_path": "ui/views", "widgets_path": "ui/widgets/common" } ``` -------------------------------- ### Conditionally Registering Service by Environment (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/service-locator.md Shows how to use the `environments` parameter when registering a dependency (like `LazySingleton`) in the Stacked framework. This restricts the registration of `NavigationService` to only the 'dev' environment. Registration will only occur if `setupLocator` is called with the matching environment. ```dart LazySingleton( classType: NavigationService, environments: {Environment.dev}, ), ``` -------------------------------- ### Implementing Basic FutureViewModel - Stacked Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Defines a FutureViewModel that fetches data asynchronously from a simulated server call. It extends the base class and overrides 'futureToRun' to link the ViewModel to a Future, automatically handling the execution and busy state. ```Dart class FutureExampleViewModel extends FutureViewModel { @override Future futureToRun() => getDataFromServer(); Future getDataFromServer() async { await Future.delayed(const Duration(seconds: 3)); return 'This is fetched from everywhere'; } } ``` -------------------------------- ### Basic IndexTrackingViewModel Implementation in Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/viewmodels.md Shows the minimal implementation of a ViewModel using the `IndexTrackingViewModel`. By simply extending this class, the ViewModel gains all the basic functionality for managing an index state, such as `currentIndex` and `setIndex`. ```Dart class HomeViewModel extends IndexTrackingViewModel {} ``` -------------------------------- ### Extracting Docusaurus Translations (Bash) Source: https://github.com/stacked-org/stacked-docs/blob/master/contributing/translation.md This Bash command extracts translatable text strings from your project and initializes the necessary JSON translation files for a given locale. Replace `{locale}` with the target locale. ```bash npm run write-translations -- --locale {locale} ``` -------------------------------- ### Adding New Stacked Dialog | Shell Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md Use this command to generate a new Dialog component for your Stacked project. It typically includes creating a DialogModel and unit tests by default, and adds the dialog to the application's configuration. ```shell stacked create dialog error ``` -------------------------------- ### Defining Stacked ViewModel Base Class (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/01-how-it-works.md Shows the simplest form of a ViewModel in the Stacked framework. A ViewModel is a standard Dart class that extends `BaseViewModel` to gain access to Stacked's state management capabilities, such as triggering UI updates. ```dart class CounterViewModel extends BaseViewModel {} ``` -------------------------------- ### Marking Mock Creation Location in Test Helpers (Dart) Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/tooling/stacked-cli.md Place this comment identifier in your `test/helpers/test_helpers.dart` file, typically below the last `getAndRegisterService` call that creates a mock, so the Stacked CLI can automatically add new mock service creation logic when generating services. ```dart // @stacked-mock-create ``` -------------------------------- ### Mixing FormStateHelper with Other ViewModels | Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/getting-started/04-form-basics.md Demonstrates how to combine the form functionality (provided by `FormStateHelper`) with ViewModels that already extend other Stacked ViewModel types like `FutureViewModel`. By mixing in `FormStateHelper` and implementing `FormViewModel`, the ViewModel gains access to form-specific properties and methods while retaining its original behavior. ```dart // Original class that you want to add form functionality to class ContentViewModel extends FutureViewModel { ... } // Do instead class ContentViewModel extends FutureViewModel with FormStateHelper implements FormViewModel { ... } ``` -------------------------------- ### ViewModel Handling Data Fetching (Problematic) - Dart Source: https://github.com/stacked-org/stacked-docs/blob/master/docs/in-depth/services.md Illustrates a common but discouraged practice where a ViewModel directly performs data fetching using HTTP and JSON deserialization. It shows tightly coupled data fetching, validation, and deserialization logic within the ViewModel itself. This approach lacks separation of concerns and makes testing difficult. ```dart class HomeViewModel extends BaseViewModel { List _artists = []; Future fetchArtists() async { // #1: Structure the http request final response = await http.get(Uri.https('venu.is', '/artists')); // #2: Validate the request is successful if (response.statusCode < 400) { // #3: Convert the response into a map final responseBodyAsMap = jsonDecode(response.body); // #4: Get relevant data from the response final artistMaps = responseBodyAsMap['data'] as List>; // #5: Deserialize into a list of artists _artists = artistMaps.map(Artist.fromJson).toList(); } } } class Artist { final String name; final String coverImage; Artist({required this.name, required this.coverImage}); factory Artist.fromJson(Map data) => Artist( name: data['name'], coverImage: data['coverImage'], ); } ```