<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aghiad Odeh on Medium]]></title>
        <description><![CDATA[Stories by Aghiad Odeh on Medium]]></description>
        <link>https://medium.com/@aghiadodeh?source=rss-321766499566------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*92HL2FVdspyFGtpO13TQIA.png</url>
            <title>Stories by Aghiad Odeh on Medium</title>
            <link>https://medium.com/@aghiadodeh?source=rss-321766499566------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:23:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aghiadodeh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter share packages with apps via Monorepo — Flutter CLI]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-share-packages-with-apps-via-monorepo-flutter-cli-efc7313d828f?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/efc7313d828f</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 13:20:44 GMT</pubDate>
            <atom:updated>2024-11-20T13:33:53.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*eP-fnnlbfA1k4tJcGcNy6g.png" /><figcaption>Monorepo workspace</figcaption></figure><h3>Flutter share packages with apps via Monorepo — Flutter CLI</h3><h3>What is a Monorepo?</h3><p>A monorepo is a single repository containing <strong>multiple distinct projects</strong>, with <strong>well-defined relationships</strong>.</p><p>Imagine you have multiple apps and they have shared Theme, Widgets, Models, REST APIs and Business logic.</p><p>You need a way to make sharing code with these applications more easy,</p><p>It is good idea to separating our code into isolated packages and share these packages with our applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*DhHdfyGhFUxgFgc_SNeKsQ.png" /><figcaption>Flutter Monorepo workspace</figcaption></figure><h3>Create Monorepo workspace:</h3><p>in this article we will use “xflutter_cli” it is CLI tool helps you to generates and modifies your Flutter components based on schematic</p><p><a href="https://xflutter-cli.com/cli/create/monorepo-workspace">Monorepo Workspace | XFlutter CLI</a></p><p>This tool will manage your monorepo workspace including:</p><ul><li>Add new application to workspace.</li><li>Add new package to workspace and share it between applications.</li><li>generate new screen, form, REST-API CRUD, data model and more in any package or app through terminal commands .</li></ul><p>Let’s start creating our monorepo workspace with “xflutter_cli” tool:</p><p>Make sure to activate “xflutter_cli” and “melos” globally before starting:</p><pre># activate xflutter_cli globally<br>dart pub global activate xflutter_cli<br><br># activate melos globally<br>dart pub global activate melos</pre><p>Create flutter monorepo workspace using “xflutter_cli”:</p><pre>xflutter_cli create --template=workspace</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nea1Qapatftx21cW5DKtsw.png" /><figcaption>Create Flutter monorepo workspace with xflutter_cli</figcaption></figure><p>“xflutter_cli” need to know some info like:</p><ul><li>monorepo workspace name</li><li>if you want to create application in workspace</li><li>new application name</li><li>new application package name</li></ul><p>After this step “xflutter_cli” will generate core package which contains:</p><ul><li>(<strong>theme</strong>): generate main colors &amp; themes.</li><li>(<strong>events</strong>): initialize “event_bus” package with common events.</li><li>(<strong>models</strong>): generate core models like “BaseResponse”, “ListResponse” and “UiMessage”.</li><li>(<strong>storage</strong>): initialize “shared_preferences” and “secure_storage” packages</li><li>(<strong>utilities</strong>): generate utilities files like (debouncer, logger, http_interceptor).</li><li>(<strong>extensions</strong>): generate extensions to add some functionality to existing libraries.</li><li>(<strong>widgets</strong>): generate reusable widgets like buttons, loaders, animations, text-fields and more.</li><li>(<strong>state-management</strong>): generate core state-management like “BaseViewModel”.</li><li>(<strong>network</strong>): generate network base components like “BaseRepository” and “Connectivity”.</li></ul><p>After “xflutter_cli” generates you monorepo workspace, your workspace will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*nI_JMw9ISl4wBMejDnGJbQ.png" /><figcaption>Flutter monorepo core package</figcaption></figure><h3>Initialize Flutter Monorepo Workspace:</h3><p>When “xflutter_cli” finish creating packages, it will install “melos” which is tool used to help manage Dart projects with multiple packages,</p><p>and “melos bs” command will executed automatically.</p><p>“melos bs” command works on:</p><ul><li>initialize the monorepo workspace.</li><li>link local packages together via `pubspec_overrides.yaml`.</li><li>recursively install all package dependencies.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CetWMLB9bjsoqHwM2PnKxw.png" /><figcaption>Running melos bs</figcaption></figure><p>Melos Official Documentation:</p><p><a href="https://melos.invertase.dev/">Melos</a></p><p>You can see “xflutter_cli.yaml” in your workspace, it is configuration file which contains all workspace applications and packages with necessary information.</p><pre># workspace name<br>workspace: flutter_monorepo_workspace<br><br># xflutter_cli version when you initialize your application,<br>#<br># If you upgrade the version of the tool and find major changes between the latest version and the version that initializes your application,<br># you can downgrade version manually by run command:<br># dart pub global activate xflutter_cli 2.5.1<br>version: 2.5.1<br><br># formatting line width<br># tool will format the dart files after Generating by running:<br># dart format . -l {format_line_width}<br>format_line_width: 140<br><br># run &quot;dart fix --apply&quot; after execute generate and make commands<br># this will make your code more clear, you can configure linter with `analysis_options.yaml`<br>apply_dart_fix: true<br><br># project modules<br>modules:<br>  # module environment<br>  # Don&#39;t modify the env values, changes may throw exceptions when you run any command<br>  - env:<br>      # architecture of module<br>      architecture: layers<br>      <br>      # module template (`app` or `package`)<br>      template: app<br>      <br>      # the tool will generate and modify all components which located in this directory <br>      # `main.dart` path for `app` template<br>      # `{package_path}/src` for `package` template<br>      base: apps/customer_app/lib<br>      <br>      # path of `pubspec.yaml`<br>      path: apps/customer_app<br>      <br>      # project name (same of name in `pubspec.yaml`)<br>      name: customer_app<br>      <br>      # machine Flutter version when initialize the module<br>      flutter_version: 3.24.1<br><br>    # xflutter_cli generate configuration<br>    generate:<br>      # avoid generate files<br>      # skip:<br>        # - data/models/ui_models/ui_message/ui_message.dart<br>        # - models/responses/list_response/list_response.dart<br>        <br>      # run `dart run build_runner build --delete-conflicting-outputs`<br>      # after generate screen, model or crud<br>      run_build_runner: true<br><br>      # overwrite file if exists<br>      overwrite: false<br>    <br>  - env:<br>      architecture: layers<br>      template: package<br>      base: packages/core/lib/src<br>      path: packages/core<br>      name: core<br>      flutter_version: 3.24.1<br>    generate:<br>      run_build_runner: true<br>      overwrite: false<br>  - env:<br>      architecture: layers<br>      template: app<br>      base: apps/admin_app/lib<br>      path: apps/admin_app<br>      name: admin_app<br>      flutter_version: 3.24.1<br>    generate:<br>      run_build_runner: true<br>      overwrite: false<br>  - env:<br>      architecture: layers<br>      template: package<br>      base: packages/products/lib/src<br>      path: packages/products<br>      name: products<br>      flutter_version: 3.24.1<br>    generate:<br>      run_build_runner: true<br>      overwrite: false<br>  - env:<br>      architecture: modules<br>      template: package<br>      base: packages/orders/lib/src<br>      path: packages/orders<br>      name: orders<br>      flutter_version: 3.24.1<br>    generate:<br>      run_build_runner: true<br>      overwrite: false</pre><h3>Generate new applications &amp; packages in existing workspace:</h3><p>open terminal at <strong>workspace root</strong> path and enter these commands</p><p>for creating a new <strong><em>application</em></strong>:</p><pre>xflutter_cli create --name=admin_app --package=com.myorg</pre><p>for creating a new <strong><em>package</em></strong>:</p><pre>xflutter_cli create --template=package --name=orders</pre><p>and “xflutter_cli” will execute “melos bs” again to include generated package in the existing applications.</p><h3>Running “xflutter_cli” command in monorepo workspace:</h3><p>When you need to generate some component like (screen, form, remote CRUD…), you have multiple apps and packages in your workspace, so you need to tell “xflutter_cli” where the command should be executed through “src” option</p><pre>xflutter_cli &lt;command&gt; &lt;option&gt; --src={destination_module}</pre><p>now if we need to generate a new screen in admin app you need to use option “<strong><em>src</em></strong>” like this:</p><pre>xflutter_cli g screen --src=admin_app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hk__V_wxHkp22Xfp.png" /></figure><p>If you didn’t pass “src” in your command, “xflutter_cli” will ask you about what module you want to execute command in.</p><h3>Display Workspace graph:</h3><p>You maybe need to graph to display your workspace applications and packages with relationships between them.</p><p>“xflutter_cli” provides a command to generate a graph for workspace:</p><pre>xflutter_cli graph</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V_hcyMD1OFkyGCH1.png" /></figure><h4>generated workspace graph:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JbkJhEmFVZrwzBHE.png" /><figcaption>Flutter Monorepo graph</figcaption></figure><p>The image above is make any one confused, it is difficult to track relationships, so you need to hover on specific app/package in sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ljE5bds3jrJRjcX.png" /><figcaption>Flutter Monorepo graph with relationships</figcaption></figure><p>Highlighting apps and packages make the graph more clear, and let’s explain what these colors mean:</p><ul><li>Blue: the hovered module.</li><li>Purple: modules that depend on the hovered module.</li><li>Green: modules that the hovered module depends on.</li></ul><p>in the image above it means:</p><ul><li>“Products” is the hovered module.</li><li>“AdminApp” and “CustomerApp” depending on “Products” module.</li><li>“Products” is depending on “Core” module.</li></ul><h3>Sharing Products list from “products” package to Admin and Customer Apps:</h3><p>We will use “xflutter_cli” to generate some products components:</p><pre># add new package &quot;products&quot; to workspace with `layers` architecture<br>xflutter_cli create --template=package --name=products --architecture=layers<br><br># generate @freezed model from json file<br>xflutter_cli g model --src=products<br><br># generate data layer (repository and retrofit rest-client) <br># for (create, update, read, delete) APIs<br># <br># entity: Product<br># local-database: generate offline layer for caching products<br># crud-endpoint: default will be &quot;product&quot;, <br># but we have custom endPoint (&quot;shop/products&quot;)<br>xflutter_cli g remote --src=products --entity-name=Product --local-database --end-point=shop/products<br><br># generate shared products-screen<br># --tablet: generate mobile &amp; tablet screens<br># --theme: add `Theme.of(Context)` to parent of tree widget<br># --state-management: generate screen including viewModel with lifecylce-awareness<br># --path: path of generated screen<br>xflutter_cli g screen --src=products --tablet --theme --state-management --path=ui/screens/products_list<br><br># generate pagination logic it will generate &quot;pagingController&quot; <br># and link products_repository with products_list_viewmodel.<br># path explain: <br># 1- entity-name: Product<br># 2- viewmodel: ui/screens/products_list/viewmodels/products_list_viewmodel.dart<br># 3- repository: data_source/repositories/products/products_repository.dart<br>xflutter_cli g p --src=products --entity-name=Product --path=viewmodel=products_list_viewmodel:repository=products_repository</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*O6u_cfL-Vj9GanJjeI2oRA.png" /><figcaption>generated products crud</figcaption></figure><p>now let’s edit our product_card Widget which generated at: “packages/products/lib/src/ui/screens/products/widgets/product_card_widget.dart”</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;../../../../models/data/product/product.dart&#39;;<br><br>class ProductCardWidget extends StatelessWidget {<br>  final Product product;<br>  const ProductCardWidget(this.product, {super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Container(<br>      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),<br>      padding: const EdgeInsets.all(10),<br>      child: Row(<br>        children: [<br>          // product image<br>          if (product.thumbnail != null)<br>            Image.network(<br>              product.thumbnail!,<br>              width: 100,<br>              height: 100,<br>            ),<br><br>          // product title<br>          Text(product.title ?? &quot;&quot;),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>and include “ProductListWidget” in products mobile &amp; tablet screens:</p><pre>// packages/products/lib/src/ui/screens/products_list/mobile/products_list_mobile_screen.dart<br><br>import &#39;../widgets/products_list_widget.dart&#39;;<br>import &#39;package:products/src/mediators/paging/products_paging_controller.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;../viewmodels/products_list_viewmodel.dart&#39;;<br>import &#39;package:core/core.dart&#39;;<br><br>class ProductsListMobileScreen extends StatelessWidget {<br>  const ProductsListMobileScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return InstanceBuilder&lt;ProductsListViewModel&gt;(<br>      builder: (ProductsListViewModel viewModel) {<br>        return ProductsListWidget(<br>          // injected &quot;ProductsPagingController&quot; by getIt<br>          controller: getIt&lt;ProductsPagingController&gt;(),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>Let’s generate product screens in admin &amp; customer apps:</p><pre># generate admin products-screen<br>xflutter_cli g screen --src=admin_app --path=ui/screens/admin_products --router<br><br># generate customer products-screen<br>xflutter_cli g screen --src=customer_app --path=ui/screens/customer_products --router</pre><p>and let’s call “products_screen” from “products” package to admin &amp; customer apps:</p><pre>// admin_products_screen.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:products/products.dart&#39;;<br>import &#39;package:auto_route/auto_route.dart&#39;;<br><br>@RoutePage(name: &#39;adminProducts&#39;)<br>class AdminProductsScreen extends StatefulWidget {<br>  const AdminProductsScreen({super.key});<br><br>  @override<br>  State&lt;AdminProductsScreen&gt; createState() =&gt; _AdminProductsScreenState();<br>}<br><br>class _AdminProductsScreenState extends State&lt;AdminProductsScreen&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return const ProductsScreen(); // &lt;-- add products_screen<br>  }<br>}</pre><p>and same thing for customer_products_screen.dart</p><p>add “Configuredependencies();” in “main.dart” which configure all required dependencies:</p><pre>void main() {<br>  // ...<br>  <br>  // configure dependencies with `dev` environment<br>  const environment = Environment(Environment.dev);<br><br>  // inject `core`dependencies (Dio &amp; environments)<br>  await configureCoreDependencies(environment: environment);<br><br>  // inject `products` dependencies (ProductsRepository &amp; DataSources)<br>  await configureProductsDependencies(environment: environment);<br><br>  // inject current app dependencies<br>  await configureAppDependencies(environment: environment);<br>  runApp(/* */);<br>}</pre><p>and don’t forget checking server URL in “packages/core/lib/src/environments/environments.dart”:</p><pre>abstract class AppEnvironment {<br>  /// size of chuck when fetch data with pagination<br>  int get perPage =&gt; 25;<br><br>  /// [BaseOptions.baseUrl] for [Dio]<br>  String get baseUrl;<br>}<br><br>class TestEnvironment extends AppEnvironment {<br>  @override<br>  String get baseUrl =&gt; &#39;https://test.backend.com&#39;;<br>}<br><br>class DevelopmentEnvironment extends AppEnvironment {<br>  @override<br>  String get baseUrl =&gt; &#39;http://192.168.0.3:3000&#39;;<br>}<br><br>class ProductionEnvironment extends AppEnvironment {<br>  @override<br>  String get baseUrl =&gt; &#39;https://live.backend.com&#39;;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6HKvLSlM8WdMqZtHdc52Q.png" /></figure><h3>Github backend example:</h3><p><a href="https://github.com/aghiadodeh/nodejs-test">GitHub - aghiadodeh/nodejs-test: NodeJs Simple Server to test dummy json apis</a></p><h3>Github flutter monorepo example:</h3><p><a href="https://github.com/aghiadodeh/xflutter_cli/tree/main/flutter_monorepo_workspace">xflutter_cli/flutter_monorepo_workspace at main · aghiadodeh/xflutter_cli</a></p><h3>Official Documentation:</h3><ul><li><a href="https://xflutter-cli.com/architecture/monorepo">Monorepo | XFlutter CLI</a></li><li><a href="https://xflutter-cli.com/cli/create/monorepo-workspace">Monorepo Workspace | XFlutter CLI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efc7313d828f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Dependency Injection with Lifecycle Awareness]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-dependency-injection-with-lifecycle-awareness-538b726ea67c?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/538b726ea67c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[lifecycle-management]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 09:13:29 GMT</pubDate>
            <atom:updated>2025-05-08T06:46:04.901Z</atom:updated>
            <content:encoded><![CDATA[<p>In Flutter applications, managing dependencies efficiently across different screens and flows can become complex, especially when dealing with multiple dependencies that have varying lifecycles.</p><h3>What is Dependency Injection?</h3><p>Dependency Injection (DI) is a powerful design pattern that helps separate concerns by decoupling object creation from business logic. It improves code maintainability, scalability, and testability, especially in complex applications.<br>In Flutter, DI becomes essential for managing services, repositories, and view models that various components of the app depend on. The <a href="https://pub.dev/packages/get_it">get_it</a> package is one of the most popular DI solutions for Flutter, providing an easy way to register and resolve dependencies. However, as applications grow, using <a href="https://pub.dev/packages/get_it">get_it</a> manually can become cumbersome, leading to a need for more automation and advanced features like scoped dependencies.<br>This is where the <a href="https://pub.dev/packages/injectable">injectable</a> package comes into play, providing automatic code generation and enhanced scope management.</p><h3>Understand the problem that DI solves</h3><h4>let’s examine how we might manage dependencies without DI:</h4><p>Let’s imagine we have a viewModel that needs to fetch data from a repository, and the repository fetches the data from remoteDataSource and localDataSource</p><p><strong>Example Without DI:</strong></p><pre>class Database {<br>  final Directory _directory;<br>  Database(this._directory);<br>}<br><br>class LocalDataSource {<br>  final Database _database;<br>  LocalDataSource(this._database);<br>}<br><br>class RemoteDataSource {<br>  final Dio _dio;<br>  RemoteDataSource(this._dio);<br>}<br><br>class Repository {<br>  final LocalDataSource _localDataSource<br>  final RemoteDataSource _remoteDataSource;<br>  Repository(this._localDataSource, this._remoteDataSource);<br>}<br><br>class ViewModel {<br>  final Repository _repository;<br>  ViewModel(this._repository);<br>}</pre><p><strong>Creating Instances Without DI:</strong></p><p>Here’s how you would create an instance of ViewModel manually:</p><pre>void main() {<br>  final directory = await getApplicationDocumentsDirectory();<br>  final database = Database(directory);<br>  final dio = Dio()<br>      ..transformer = BackgroundTransformer()<br>      ..options = BaseOptions(<br>        connectTimeout: const Duration(seconds: 60),<br>        receiveTimeout: const Duration(seconds: 60),<br>        sendTimeout: const Duration(seconds: 60),<br>        baseUrl: &#39;https://www.xflutter-cli.com/api&#39;,<br>      );<br><br>  final localDataSource = LocalDataSource(database);<br>  final remoteDataSource = RemoteDataSource(dio);<br><br>  final repository = Repository(localDataSource, remoteDataSource);<br><br>  final viewModel = ViewModel(repository);<br>}</pre><p><strong>What’s Wrong with This Approach?</strong></p><p>1. <strong>Tight Coupling</strong>: Each layer (e.g., ViewModel, Repository, DataSource) directly depends on its lower layers. If you decide to change Database to another database implementation, you need to update several files.</p><p>2. <strong>Repetition</strong>: Every time you need an instance of ViewModel, you must re-create its dependencies manually.</p><p>3. <strong>Hard-to-Test Code</strong>: Testing is challenging because each dependency must be mocked manually and passed to the class being tested.</p><p>4. <strong>Scalability Issues</strong>: In a large application, managing these dependencies manually becomes unmanageable and error-prone.</p><p>Dependency Injection addresses all of these issues by introducing a systematic way to manage dependencies.</p><h3><strong>What is a Service Locator?</strong></h3><p>A Service Locator is a design pattern that provides a centralized registry for managing dependencies. Instead of creating dependencies manually in multiple places, you register them once in the service locator and retrieve them wherever needed.</p><p>With a service locator, your code no longer needs to worry about <strong>how</strong> dependencies are created or managed; it only focuses on <strong>using</strong> them.</p><p><strong>Benefits of a Service Locator:</strong></p><p>1. <strong>Centralized Dependency Management</strong>: All dependencies are registered in one place, making it easier to configure and manage them.</p><p>2. <strong>Reusability</strong>: The same dependency instance can be reused across different parts of the application.</p><p>3. <strong>Improved Testability</strong>: Dependencies can be swapped out for mock implementations during testing.</p><h4>Working with <a href="https://pub.dev/packages/get_it">get_it</a>:</h4><p><a href="https://pub.dev/packages/get_it">get_it</a> serves as a simple service locator, allowing developers to register and retrieve dependencies. It works well in smaller apps or straightforward use cases. Here’s why many developers start with <a href="https://pub.dev/packages/get_it">get_it</a>:</p><ol><li><strong>Simplicity</strong>: Registering services, repositories, and view models in get_it is straightforward and minimalistic.</li><li><strong>Flexibility</strong>: It supports registering singletons, factories, and even instances on demand.</li><li><strong>Global Access</strong>: Once a dependency is registered, it can be accessed globally throughout the app using the locator.</li></ol><pre>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:path_provider/path_provider.dart&#39;;<br>import &#39;package:dio/dio.dart&#39;;<br><br>final GetIt locator = GetIt.instance;<br><br>Future&lt;void&gt; setupLocator() async {<br>  // Register `Directory` as a factory (note: asynchronous dependencies must still be awaited)<br>  final directory = await getApplicationDocumentsDirectory();<br>  locator.registerFactory&lt;Directory&gt;(() =&gt; directory);<br><br>  // Register `Database`<br>  locator.registerFactory&lt;Database&gt;(() =&gt; Database(locator&lt;Directory&gt;()));<br><br>  // Register `Dio`<br>  locator.registerFactory&lt;Dio&gt;(<br>    () =&gt; Dio()<br>      ..transformer = BackgroundTransformer()<br>      ..options = BaseOptions(<br>        connectTimeout: const Duration(seconds: 60),<br>        receiveTimeout: const Duration(seconds: 60),<br>        sendTimeout: const Duration(seconds: 60),<br>        baseUrl: &#39;https://www.xflutter-cli.com/api&#39;,<br>      ),<br>  );<br><br>  // Register `LocalDataSource`<br>  locator.registerFactory&lt;LocalDataSource&gt;(() =&gt; LocalDataSource(locator&lt;Database&gt;()));<br><br>  // Register `RemoteDataSource`<br>  locator.registerFactory&lt;RemoteDataSource&gt;(() =&gt; RemoteDataSource(locator&lt;Dio&gt;()));<br><br>  // Register `Repository`<br>  locator.registerFactory&lt;Repository&gt;(<br>    () =&gt; Repository(<br>      locator&lt;LocalDataSource&gt;(),<br>      locator&lt;RemoteDataSource&gt;(),<br>    ),<br>  );<br><br>  // Register `ViewModel`<br>  locator.registerFactory&lt;ViewModel&gt;(() =&gt; ViewModel(locator&lt;Repository&gt;()));<br>}</pre><p><strong>Using the Locator:</strong></p><pre>final GetIt locator = GetIt.instance;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br><br>  // Initialize the service locator<br>  await setupLocator();<br><br>  // Retrieve the ViewModel<br>  final viewModel = locator&lt;ViewModel&gt;();<br>}</pre><p>With GetIt, you no longer need to manually pass dependencies to constructors or worry about their initialization order.</p><p><strong>Why is this Better?</strong></p><p>• <strong>Cleaner Code</strong>: The dependency creation logic is moved out of the business logic.</p><p>• <strong>Scalability</strong>: Adding or modifying dependencies requires minimal changes.</p><p>• <strong>Ease of Testing</strong>: During testing, you can override dependencies in the service locator with mock implementations.</p><h3><strong>Dependency Injection with injectable Package</strong></h3><p>As your Flutter app becomes more complex, you’ll start to notice several challenges with <a href="https://pub.dev/packages/get_it">get_it</a>:</p><ol><li><strong>Manual Registrations</strong>: Manually registering dependencies can become error-prone as the number of services and dependencies grows.</li><li><strong>Maintenance Overhead</strong>: It becomes harder to manage dependencies across large applications, especially when you need to refactor or introduce new components.</li><li><strong>Testing</strong>: Setting up mock services for testing requires manually overriding or un-registering services, which can be tedious.</li><li><strong>Scopes</strong>: Managing the lifecycle of dependencies, such as creating and destroying services for specific user sessions or screens, becomes tricky.</li></ol><p>This is where <a href="https://pub.dev/packages/injectable">injectable</a> comes in. The injectable package builds on top of <a href="https://pub.dev/packages/get_it">get_it</a>, automating the process of registering dependencies and providing better support for managing scoped dependencies. It uses annotations and code generation to register services, repositories, and view-models, reducing boilerplate and improving maintainability.</p><h3><strong>Setting Up injectable:</strong></h3><h4>1. Installing package:</h4><pre>dependencies:<br>  get_it: ^8.0.1<br>  injectable: ^2.5.0<br><br>dev_dependencies:<br>  build_runner: ^2.4.11<br>  injectable_generator: ^2.6.2</pre><h4>2. <strong>Annotate Your Classes:</strong></h4><pre>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;package:dio/dio.dart&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;package:path_provider/path_provider.dart&#39;;<br><br>@module<br>abstract class AppModule {<br>  @preResolve<br>  @lazySingleton<br>  Future&lt;Directory&gt; provideDocumentsDirectory() =&gt; getApplicationDocumentsDirectory();<br><br>  @lazySingleton<br>  Dio get dio =&gt; Dio()<br>    ..transformer = BackgroundTransformer()<br>    ..options = BaseOptions(<br>      connectTimeout: const Duration(seconds: 60),<br>      receiveTimeout: const Duration(seconds: 60),<br>      sendTimeout: const Duration(seconds: 60),<br>      baseUrl: &#39;https://www.xflutter-cli.com/api&#39;,<br>    );<br>}<br><br>@injectable<br>class LocalDataSource {<br>  final Database database;<br>  LocalDataSource(this.database);<br>}<br><br>@injectable<br>class RemoteDataSource {<br>  final Dio dio;<br>  RemoteDataSource(this.dio);<br>}<br><br>@injectable<br>class Repository {<br>  final LocalDataSource localDataSource;<br>  final RemoteDataSource remoteDataSource;<br>  Repository(this.localDataSource, this.remoteDataSource);<br>}<br><br>@injectable<br>class ViewModel {<br>  final Repository repository;<br>  ViewModel(this.repository);<br>}</pre><h4>3. <strong>Generate the Dependency Injection Setup:</strong></h4><pre>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;injectable.config.dart&#39;; // auto generated file<br><br>/// manage dependencies<br>@InjectableInit()<br>Future&lt;void&gt; configureAppDependencies() async {<br>  await GetIt.instance.init();<br>}</pre><p>Run the code generation command:</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><h4>4. <strong>Initialize Dependencies:</strong></h4><p>In your main function, initialize the dependencies before using them.</p><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br><br>  // Initialize dependencies<br>  await configureAppDependencies();<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    // Use the ViewModel with all its dependencies resolved automatically.<br>    // Retrieve ViewModel from the service locator<br>    final viewModel = locator&lt;ViewModel&gt;();<br><br>    return MaterialApp(/* properties */);<br>  }<br>}</pre><h4><strong>How It Works?</strong></h4><p>1. <strong>Module Class (</strong>AppModule<strong>)</strong></p><p>Provides configuration for third-party dependencies like Directory and Dio.</p><ul><li>@module: Indicates a class that provides dependency configuration.</li><li>@preResolve: Allows asynchronous initialization for Directory.</li></ul><p>2. <strong>Injectable Annotations</strong></p><ul><li>@injectable: Marks a class as injectable.</li><li>@lazySingleton: Creates a single instance and reuses it throughout the app.</li></ul><p>3. <strong>Code Generation</strong></p><ul><li>The build_runner generates a file (injectable.config.dart) that wires all dependencies. This simplifies manual registration in a service locator.</li></ul><p>4. <strong>Automatic Dependency Resolution</strong></p><ul><li>Dependencies are resolved automatically without manual wiring, making it easy to maintain and test.</li></ul><h3>Difference Between @injectable and @singleton</h3><p>While both @injectable and @singleton annotations help with automatic registration, they serve different purposes, particularly in how they manage object lifecycles.</p><h4>@injectable: Default Behavior</h4><ul><li><strong>Instance Creation</strong>: By default, classes annotated with @injectable are created every time they are requested.<br>This means that the same class can have multiple instances throughout the app.</li><li><strong>Use Case</strong>: This is useful for classes that should not be reused globally,<br>such as classes with short lifecycles or objects that need to be created multiple times (e.g., temporary objects for specific screens).</li></ul><h4>@singleton: Singleton Behavior</h4><ul><li><strong>Global Instance</strong>: When you use @singleton, the annotated class is created once and shared throughout the app.<br>This means that every time the class is requested, the same instance is returned.</li><li><strong>Memory Efficiency</strong>: Singletons are ideal for services that should be reused globally, such as repositories, database connections, or network services.<br>This ensures that the service is only initialized once, avoiding unnecessary memory usage.</li></ul><h4>Key Differences:</h4><ol><li><strong>Instance Management</strong>:</li></ol><ul><li>@injectable: Creates a new instance every time it is requested.</li><li>@singleton: Creates a single instance that is reused throughout the app.</li></ul><p><strong>2. Lifecycle</strong>:</p><ul><li>@injectable: Shorter lifecycle, suitable for objects that need to be re-created frequently.</li><li>@singleton: Longer lifecycle, typically used for services that should persist across the entire app lifecycle.</li></ul><p><strong>3. Memory Usage</strong>:</p><ul><li>@injectable: More memory usage in cases where multiple instances are created.</li><li>@singleton: More memory efficient, as the same instance is shared.</li></ul><h3>What is Lifecycle Awareness?</h3><p>Lifecycle awareness is the ability of a component or dependency to adapt its behavior or scope based on the lifecycle state of its owner (e.g., a screen, widget, or service). This ensures that resources are managed efficiently, avoiding memory leaks, redundant operations, or unnecessary resource consumption.</p><p>In the context of Flutter, lifecycle awareness is crucial for managing dependencies that should exist only during a specific phase of the application (e.g., when a screen is active or a widget is mounted).</p><p><strong>Why Lifecycle Awareness is Important</strong></p><p>1. <strong>Resource Management</strong>:</p><ul><li>For dependencies like database connections, network clients, or animations, keeping them alive after they are no longer needed can waste memory and processing power. Lifecycle awareness helps clean them up automatically.</li></ul><p>2. <strong>Avoid Memory Leaks</strong>:</p><ul><li>Without lifecycle awareness, dependencies might remain in memory longer than necessary, leading to memory leaks in your application.</li></ul><p>3. <strong>Scoped Dependencies</strong>:</p><ul><li>Lifecycle-aware dependencies can be created when needed and destroyed when their associated screen or component is removed, ensuring proper isolation and scope.</li></ul><h3>What is Scoped Singletons?</h3><p><strong>Scopes</strong> allow registration of related dependencies in a different scope, so they can be initialized only when needed and disposed of when they’re not.</p><p>One of the most efficient strategies for managing memory in Flutter applications is to mix singleton usage with temporary objects, and this is where <strong>scoped singletons</strong> come into play.</p><p><strong>Scoped singletons</strong> provide a mechanism to share the same instance of a class (like a repository) across multiple screens or processes, while ensuring it is properly cleaned up when no longer needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*n0EtGCYqYGtF2RpBbK1NPw.png" /><figcaption>Auth Module with DI using scoped singletons</figcaption></figure><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:retrofit/retrofit.dart&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br><br>@LazySingleton(scope: &#39;authentication&#39;)<br>@RestApi()<br>abstract class AuthenticationRemoteDataSource {<br>  @factoryMethod<br>  factory AuthenticationRemoteDataSource(Dio dio) = _AuthenticationRemoteDataSource;<br><br>  @POST(&#39;/auth/login&#39;)<br>  Future&lt;BaseResponse&lt;dynamic&gt;&gt; login({<br>    @Body() required Map&lt;String, dynamic&gt; data,<br>  });<br><br>  @POST(&#39;/auth/verify&#39;)<br>  Future&lt;BaseResponse&lt;dynamic&gt;&gt; verifyPinCode({<br>    @Body() required Map&lt;String, dynamic&gt; data,<br>  });<br>}</pre><pre>@LazySingleton(scope: &#39;authentication&#39;)<br>class AuthenticationRepository {<br>  final AuthenticationRemoteDataSource _remoteDataSource;<br>  AuthenticationRepository(this._remoteDataSource);<br><br>  Future&lt;BaseResponse&lt;dynamic&gt;&gt; login(LoginRequest request) async {<br>    final response = await _remoteDataSource.login(request.toJson());<br>    return response;<br>  }<br><br>  // ...<br>}</pre><p>Run the code generation command:</p><pre>flutter pub run build_runner build --delete-conflicting-outputs </pre><p>The injectable package give ability to register scope by “init{scopeName}Scope()” auto generated method.</p><p>Now we can register the “authentication” scope with all dependencies (“AuthenticationRepository” &amp; “AuthenticationRemoteDataSource”) when login screen created.</p><pre>class LoginScreen extends StatefulWidget {<br>  const LoginScreen({super.key});<br><br>  @override<br>  State&lt;LoginScreen&gt; createState() =&gt; _LoginScreenState();<br>}<br><br>class _LoginScreenState extends State&lt;LoginScreen&gt; {<br>  @override<br>  void initState() {<br>    // register `authentication` dependencies<br>    GetIt.instance.initAuthenticationScope();<br>    <br>    // register `login` dependencies<br>    GetIt.instance.initLoginScope();<br>    super.initState();<br>  }<br><br>  @override<br>  void dispose() {<br>    // clear `login` scope from memory<br>    GetIt.instance.dropScope(&#39;login&#39;);<br>  }<br>}<br><br>@LazySingleton(scope: &#39;login&#39;)<br>class LoginViewModel {<br>  // access the Repository from registered &#39;authentication&#39; scope<br>  final AuthenticationRepository _authenticationRepository;<br>  LoginViewModel(this._authenticationRepository);<br><br>  Future&lt;void&gt; login() async {<br>    final response = await _authenticationRepository.login();<br>    // handle success response...  <br>  }<br>}</pre><p>and then let’s implement the “VerifyScreen”:</p><pre>class VerifyScreen extends StatefulWidget {<br>  const VerifyScreen({super.key});<br><br>  @override<br>  State&lt;VerifyScreen&gt; createState() =&gt; _VerifyScreenState();<br>}<br><br>class _VerifyScreenState extends State&lt;VerifyScreen&gt; {<br>  @override<br>  void initState() {<br>    // register `verify` dependencies<br>    GetIt.instance.initVerifyScope();<br>    super.initState();<br>  }<br><br>  @override<br>  void dispose() {<br>    // clear `verify` scope from memory<br>    GetIt.instance.dropScope(&#39;verify&#39;);<br>    <br>    // clear `authentication` scope from memory<br>    GetIt.instance.dropScope(&#39;authentication&#39;);<br>    super.dispose();<br>  }<br>}<br><br>@LazySingleton(scope: &#39;verify&#39;)<br>class VerifyViewModel {<br>  // access the from registered &#39;authentication&#39; scope<br>  final AuthenticationRepository _authenticationRepository;<br>  VerifyViewModel(this._authenticationRepository);<br>}</pre><h4>This has the following benefits:</h4><ol><li><strong>Reduced Memory Usage</strong>: By sharing the same repository instance and its dependencies across multiple screens, you avoid creating multiple instances, which helps save memory.<br>Once the user has completed the authentication flow and navigated to the home screen, you can clean up the authentication-related dependencies, ensuring that they no longer consume memory unnecessarily.</li><li><strong>Consistent State</strong>: Using a scoped singleton allows different parts of the app (like the login screen and phone verification screen) to access the same state and data, ensuring consistency. For example, if a token is fetched in one screen, it will be accessible in the other without needing to pass data around manually.</li></ol><p>In this scenario, when the user logs in and moves to the phone verification screen, both screens will share the same instance of AuthRepository</p><h3>Automate Lifecycle management with LifecycleOwner</h3><p>the <a href="https://xflutter-cli.com/components/ui/di/lifecycle-owner">LifecycleOwner</a> is a mixin, which automates the management of <a href="https://xflutter-cli.com/architecture/dependency-injection#scopes">dependency injection scopes</a>, particularly when working with the <a href="https://pub.dev/packages/injectable">injectable</a> package.</p><p>The <strong>primary</strong> role of <a href="https://xflutter-cli.com/components/ui/di/lifecycle-owner">LifecycleOwner</a> is to manage the lifecycle of the dependencies like (ViewModel, Repository).</p><p>These dependencies are typically marked with <strong>@LazySingleton(scope: ‘scopeName’)</strong>, ensuring that it is scoped to a specific feature or flow in your application.</p><p>Furthermore, Lifecycle Owner works with <a href="https://xflutter-cli.com/architecture/dependency-injection#scopes">Dependency Injection</a>, enabling various components within the same screen to share a single instance of the ViewModel as mentioned in <a href="https://xflutter-cli.com/architecture/ui-layer/state-management#implementing-viewmodel">Login Example</a>.</p><h4>Define Lifecycle Owner DiScope Model:</h4><p>The DiScope class is at the heart of this <a href="https://xflutter-cli.com/architecture/lifecycle-awareness">Lifecycle Awareness</a> approach. It works side by side with <a href="https://xflutter-cli.com/components/ui/di/lifecycle-owner">LifecycleOwner</a> to give ability to define a scope, register its dependencies, and automatically dispose of it when it’s no longer needed.</p><p>Let’s break down what each part of DiScope does:</p><pre>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>part &#39;di_scope.freezed.dart&#39;;<br><br>@freezed<br>class DiScope with _$DiScope {<br>  const factory DiScope({<br>    /// Name of scope.<br>    required String name,<br><br>    /// Factory method to register dependencies of the scope.<br>    required GetIt Function() factory,<br><br>    /// drop scope on dispose.<br>    @Default(false) bool dispose, // Allows manual disposal<br><br>    /// Automatically drop the scope on lifecycle-owner dispose (true by default).<br>    @Default(true) bool disposeByOwner,<br><br>    /// Other scopes or dependencies that need to be registered first.<br>    @Default([]) List&lt;DiScope&gt; dependencies,<br>  }) = _DiScope;<br>}</pre><ol><li><strong>name</strong>: This is the identifier for the scope, which helps in managing and referencing the scope.</li><li><strong>factory</strong>: This is a function that initializes the scope’s dependencies. In the example above, <strong>getIt.initLoginScope()</strong> is the factory method that registers the dependencies for the login scope.</li><li><strong>dispose</strong>: Controls whether the scope can be disposed independently of its LifecycleOwner.<br>If dispose is set to true, the scope can be manually disposed outside the context of the screen lifecycle.<br>This is useful in cases where you may want to explicitly clean up resources before the screen’s lifecycle ends.</li><li><strong>disposeByOwner</strong>: This determines whether the scope is disposed when the lifecycle owner (e.g., the screen) is disposed.</li><li><strong>dependencies</strong>: This is an array of other scopes that need to be initialized before the current scope. For example, the LoginViewModel might depend on an <strong>AuthRepository</strong> which is provided by the <strong>authentication scope</strong>.</li></ol><h4>Define Lifecycle Owner mixin:</h4><pre>import &#39;dart:async&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:xflutter_cli/common/data/models/di/di_scope/di_scope.dart&#39;;<br><br>/// manage widget life-cycle with your dependencies,<br>/// and drop passed scope when widget destroyed.<br>mixin LifecycleOwner&lt;T extends StatefulWidget, Dependency extends Object&gt; on State&lt;T&gt; {<br>  /// access registered [Dependency] from child<br>  late Dependency instance;<br><br>  /// [DiScope] that [LifecycleOwner] will take care, register it on [initState] and drop it on [dispose]<br>  DiScope get diScope;<br><br>  /// save the [DiScope] list that registered by this [LifecycleOwner],<br>  ///<br>  /// [LifecycleOwner] will save the [diScope] and all its dependencies when register it,<br>  /// after check if this scope not registered before<br>  ///<br>  /// this will help you when you have multiple screen need for this scope, and you don&#39;t know which screen registered the scope,<br>  /// here you can know which scopes registered by this [LifecycleOwner]<br>  List&lt;DiScope&gt; diScopes = [];<br><br>  /// callback fired immediately after the widget is allocated in memory.<br>  void onInitState() {}<br><br>  /// callback fired when widget destroyed.<br>  void onDispose() {}<br><br>  @override<br>  void initState() {<br>    registerScope(diScope);<br>    instance = GetIt.instance.get&lt;Dependency&gt;();<br>    onInitState();<br>    super.initState();<br>  }<br><br>  /// creates a new registration [scope], with all dependencies<br>  void registerScope(DiScope scope) {<br>    // register scope dependencies<br>    for (final dependency in scope.dependencies) {<br>      registerScope(dependency);<br>    }<br><br>    // check if scope has registered before<br>    if (!GetIt.instance.hasScope(scope.name)) {<br>      // register scope<br>      scope.factory();<br><br>      // add to scopes<br>      diScopes.add(scope);<br>    }<br>  }<br><br>  @override<br>  void dispose() {<br>    onDispose();<br>    dropScope(diScope);<br>    super.dispose();<br>  }<br><br>  /// clears all registered factories and singletons in the provided [scope]<br>  Future&lt;void&gt; dropScope(DiScope scope) async {<br>    // check if scope is already registered<br>    if (GetIt.instance.hasScope(scope.name)) {<br>      if (scope.disposeByOwner) {<br>        // check if scope registered in this lifeCycle Owner<br>        final index = diScopes.indexWhere((e) =&gt; e.name == scope.name);<br>        if (index != -1) {<br>          // drop all scope dependencies<br>          await GetIt.instance.dropScope(scope.name);<br>        }<br>      } else if (scope.dispose) {<br>        // drop all scope dependencies<br>        await GetIt.instance.dropScope(scope.name);<br>      }<br>    }<br><br>    // clear scope dependencies<br>    for (final dependency in scope.dependencies) {<br>      await dropScope(dependency);<br>    }<br>  }<br>}</pre><p>With LifecycleOwner, you control the dependencies lifecycle by <strong>automatically</strong> creating an instance when the screen initializes <strong>(initState)</strong> and cleaning it from memory when the screen is disposed <strong>(dispose)</strong>.<br>This approach optimizes resource usage and ensures that only the necessary objects are kept alive as long as they are needed.</p><h4>Implementing LifecycleOwner:</h4><p>Let’s add “LifecycleOwner” to “login” and “verify” screens:</p><p>Login screen:</p><pre>class LoginScreen extends StatefulWidget {<br>  const LoginScreen({super.key});<br><br>  @override<br>  State&lt;LoginScreen&gt; createState() =&gt; _LoginScreenState();<br>}<br><br>class _LoginScreenState extends State&lt;LoginScreen&gt; <br>  with LifecycleOwner&lt;LoginScreen, LoginViewModel&gt; {<br>  <br>  // handle success login response<br>  void loginSuccess() {<br>    // navigate to verifyScreen<br>    Navigator.of(context).pushReplacement(<br>      MaterialPageRoute(builder: (_) =&gt; VerifyScreen()),<br>    );<br>  }<br><br>  @override<br>  DiScope get diScope =&gt; DiScope(<br>        name: &#39;login&#39;,<br>        factory: GetIt.instance.initLoginScope,<br>        dependencies: [<br>          DiScope(<br>            name: &#39;authentication&#39;,<br>            factory: GetIt.instance.initAuthenticationScope,<br>            disposeByOwner: false, // prevent destroy when login-screen destoyed<br>          ),<br>        ],<br>      );<br><br>  @override<br>  Widget build(BuildContext context) {<br>    // Build the UI tree<br>    return Container(); // Your actual UI here<br>  }<br>}</pre><p>Adding “disposeByOwner: false” will tell LoginScreen’s <strong>LifeCycleOwner</strong> to ignore destroying the “authentication” scope on the screen dispose.</p><p>Verify screen:</p><pre>class VerifyScreen extends StatefulWidget {<br>  const VerifyScreen({super.key});<br><br>  @override<br>  State&lt;VerifyScreen&gt; createState() =&gt; _VerifyScreenState();<br>}<br><br>class _VerifyScreenState extends State&lt;VerifyScreen&gt; {<br>  with LifecycleOwner&lt;VerifyScreen, VerifyViewModel&gt; {<br>  <br>  // handle success verify response<br>  void verifySuccess() {<br>    // navigate to homeScreen<br>    Navigator.of(context).pushReplacement(<br>      MaterialPageRoute(builder: (_) =&gt; HomeScreen()),<br>    );<br>  }<br><br>  @override<br>  DiScope get diScope =&gt; DiScope(<br>        name: &#39;verify&#39;,<br>        factory: GetIt.instance.initVerifyScope,<br>        dependencies: [<br>          DiScope(<br>            name: &#39;authentication&#39;,<br>            factory: GetIt.instance.initAuthenticationScope,<br>            dispose: true, // destroy when verify-screen destoyed<br>          ),<br>        ],<br>      );<br><br>  @override<br>  Widget build(BuildContext context) {<br>    // Build the UI tree<br>    return Container(); // Your actual UI here<br>  }<br>}</pre><p>Adding “dispose: true” will tell VerifyScreen’s <strong>LifeCycleOwner</strong> to destroy the “authentication” scope on the disposal screen, even if VerifyScreen is not the owner of the “authentication” scope (the scope that was created outside of this screen).</p><p>Don’t worry about adding “authentication” scope <strong>twice</strong>, in “Login screen” and “Verify Screen”, It will be registered only <strong>once</strong> by “Login screen”.</p><p>because <strong>LifecycleOwner</strong> will check if scope is registered before, if scope is <strong>not</strong> registered then the <strong>LifecycleOwner </strong>will register the scope, otherwise it will ignore registration.</p><h3>Benefits of Scoped Dependencies</h3><ol><li><strong>Efficient Memory Usage</strong>: By using scoped singletons, you ensure that large or complex objects (like repositories and view models) are only created when they are needed and cleaned up when they are no longer required. This prevents memory leaks and keeps the app responsive.</li><li><strong>Separation of Concerns</strong>: The dependencies of a particular feature, like login or authentication, are isolated within their own scope. This ensures that different parts of the app don’t interfere with each other and can be developed independently.</li><li><strong>Reusability</strong>: The same ViewModel, Repository, or other business logic classes can be reused across multiple components (like login, phone verification, etc.) without duplicating instances or data.</li><li><strong>Optimized Performance</strong>: By automatically cleaning up unused scopes and dependencies, the app minimizes unnecessary resource consumption, which helps maintain high performance even in complex flows.</li></ol><h3>What is next?</h3><p><a href="https://medium.com/@aghiadodeh/flutter-state-management-with-dependency-injection-f016d51515ce">Flutter State Management with Dependency Injection</a></p><h3>Full Example:</h3><p><a href="https://github.com/aghiadodeh/xflutter_cli/tree/v2.5.0/xflutter_cli_modules_application/lib/modules/authentication">xflutter_cli/xflutter_cli_modules_application/lib/modules/authentication at v2.5.0 · aghiadodeh/xflutter_cli</a></p><h3>Dependency Injection:</h3><p><a href="https://xflutter-cli.com/architecture/dependency-injection">XFlutter CLI</a></p><h3>Lifecycle Owner:</h3><p><a href="https://xflutter-cli.com/components/ui/di/lifecycle-owner">Lifecycle Owner | XFlutter CLI</a></p><h3>Lifecycle Provider:</h3><p><a href="https://www.xflutter-cli.com/components/ui/di/lifecycle-provider">Lifecycle Provider | XFlutter CLI</a></p><h3>Improve Productivity:</h3><p><a href="https://www.xflutter-cli.com/cli/intro">CLI Introduction | XFlutter CLI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=538b726ea67c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Pagination with cache data (Objectbox Database)]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-pagination-with-cache-data-objectbox-database-5d5937746828?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d5937746828</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[offline]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 17:44:47 GMT</pubDate>
            <atom:updated>2025-01-07T11:47:02.141Z</atom:updated>
            <content:encoded><![CDATA[<p>Pagination is a common technique used in apps to handle large sets of data, particularly when fetching from remote sources or when managing limited local storage.</p><p>It ensures that users don’t have to wait for an entire dataset to load at once, improving both performance and user experience.</p><p>With Flutter, the <a href="https://pub.dev/packages/animated_infinite_scroll_pagination">animated_infinite_scroll_pagination</a> package is designed to simplify pagination with an animated scrolling experience, especially for infinite lists.</p><p>It provides utilities to manage fetching pages of data incrementally and ensures smooth scrolling animations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*XA-mJcjq-QytrqvY1xTzuQ.png" /><figcaption>Flutter App layers with paging layer</figcaption></figure><p>In this article we’re going to build a Flutter App contains a list of “Products” and save this list in our local database <strong>(Objectbox database), </strong>the list will be loaded and displayed small chunks of items as the user scrolls down the screen.</p><p>In this article we’re going to use these dependencies:</p><ol><li><a href="https://pub.dev/packages/animated_infinite_scroll_pagination"><strong>animated_infinite_scroll_pagination</strong></a>: load and display small chunks of items as the user scrolls down the screen</li><li><a href="https://pub.dev/packages/retrofit"><strong>Retrofit</strong></a>: is a type-safe HTTP client for Dart, which makes it easier to connect with web services.</li><li><a href="https://pub.dev/packages/objectbox"><strong>ObjectBox</strong></a> a high-performance database for Flutter and Dart. It is designed for speed, making it suitable for applications that need real-time, offline-first data storage.</li><li><a href="https://pub.dev/packages/injectable"><strong>Injectable</strong></a>: The injectable package builds on top of <a href="https://pub.dev/packages/get_it">get_it</a>, automating the process of registering dependencies and providing better support for managing scoped dependencies</li></ol><p>here we’re going to add some dependencies to our new flutter project. Our pubspec.yaml should look something like:</p><pre>dependencies:<br>  path_provider: ^2.1.1<br>  objectbox_flutter_libs: ^4.0.2<br>  objectbox: ^4.0.2<br>  retrofit: ^4.0.1<br>  pretty_dio_logger: ^1.4.0<br>  dio: ^5.1.2<br>  animated_infinite_scroll_pagination: ^1.0.3<br>  flutterx_live_data: ^1.9.6<br>  connectivity_plus: ^6.0.3<br>  json_annotation: ^4.9.0<br>  freezed_annotation: ^2.1.0<br>  injectable: ^2.5.0<br>  get_it: ^8.0.1<br>  auto_route: ^9.2.2<br>  cupertino_icons: ^1.0.8<br>  flutter:<br>    sdk: flutter<br><br>dev_dependencies:<br>  objectbox_generator: ^4.0.2<br>  retrofit_generator: ^7.0.1<br>  freezed: ^2.5.7<br>  json_serializable: ^6.4.1<br>  injectable_generator: ^2.6.2<br>  build_runner: ^2.4.11<br>  flutter_lints: ^4.0.0<br>  flutter_test:<br>    sdk: flutter</pre><h3>1. Setup Model:</h3><p>Our Server return a list of data “<strong>Product</strong>” in Response like this:</p><pre>{<br>  &quot;message&quot;: &quot;Success&quot;,<br>  &quot;statusCode&quot;: 200,<br>  &quot;success&quot;: true,<br>  &quot;data&quot;: {<br>    &quot;total&quot;: 194,<br>    &quot;skip&quot;: 0,<br>    &quot;limit&quot;: 1,<br>    &quot;data&quot;: [<br>      {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;Essence Mascara Lash Princess&quot;,<br>        &quot;description&quot;: &quot;The Essence Mascara Lash Princess is a popular mascara known for its volumizing and lengthening effects. Achieve dramatic lashes with this long-lasting and cruelty-free formula.&quot;,<br>        &quot;category&quot;: &quot;beauty&quot;,<br>        &quot;price&quot;: 9.99,<br>        &quot;discountPercentage&quot;: 7.17,<br>        &quot;rating&quot;: 4.94,<br>        &quot;stock&quot;: 5,<br>        &quot;warrantyInformation&quot;: &quot;1 month warranty&quot;,<br>        &quot;shippingInformation&quot;: &quot;Ships in 1 month&quot;,<br>        &quot;availabilityStatus&quot;: &quot;Low Stock&quot;,<br>        &quot;returnPolicy&quot;: &quot;30 days return policy&quot;,<br>        &quot;minimumOrderQuantity&quot;: 24,<br>        &quot;brand&quot;: &quot;Essence&quot;,<br>        &quot;sku&quot;: &quot;RCH45Q1A&quot;,<br>        &quot;weight&quot;: 2,<br>        &quot;thumbnail&quot;: &quot;https://cdn.dummyjson.com/products/images/beauty/Essence%20Mascara%20Lash%20Princess/thumbnail.png&quot;,<br>        &quot;tags&quot;: [<br>          &quot;beauty&quot;<br>        ],<br>        &quot;dimensions&quot;: {<br>          &quot;width&quot;: 23.17,<br>          &quot;height&quot;: 14.43,<br>          &quot;depth&quot;: 28.01<br>        },<br>        &quot;reviews&quot;: [<br>          {<br>            &quot;rating&quot;: 2,<br>            &quot;comment&quot;: &quot;Very unhappy with my purchase!&quot;,<br>            &quot;date&quot;: &quot;2024-05-23T08:56:21.618Z&quot;,<br>            &quot;reviewerName&quot;: &quot;John Doe&quot;,<br>            &quot;reviewerEmail&quot;: &quot;john.doe@x.dummyjson.com&quot;<br>          }<br>        ],<br>        &quot;meta&quot;: {<br>          &quot;createdAt&quot;: &quot;2024-05-23T08:56:21.618Z&quot;,<br>          &quot;updatedAt&quot;: &quot;2024-05-23T08:56:21.618Z&quot;,<br>          &quot;barcode&quot;: &quot;9164035109868&quot;,<br>          &quot;qrCode&quot;: &quot;https://assets.dummyjson.com/public/qr-code.png&quot;<br>        },<br>        &quot;images&quot;: [<br>          &quot;https://cdn.dummyjson.com/products/images/beauty/Essence%20Mascara%20Lash%20Princess/1.png&quot;<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>So we’re going to create our models like this with <a href="https://pub.dev/packages/freezed">freezed</a>:</p><pre>// base_response.dart<br>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>part &#39;base_response.freezed.dart&#39;;<br>part &#39;base_response.g.dart&#39;;<br><br>@Freezed(genericArgumentFactories: true)<br>class BaseResponse&lt;T&gt; with _$BaseResponse&lt;T&gt; {<br>  const factory BaseResponse({<br>    int? statusCode,<br>    String? message,<br>    T? data,<br>    bool? success,<br>  }) = _BaseResponse&lt;T&gt;;<br><br>  factory BaseResponse.fromJson(Map&lt;String, dynamic&gt; json, T Function(Object?) fromJsonT) =&gt; _$BaseResponseFromJson(json, fromJsonT);<br>}</pre><pre>// list_response.dart<br>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>part &#39;list_response.freezed.dart&#39;;<br>part &#39;list_response.g.dart&#39;;<br><br>@Freezed(genericArgumentFactories: true)<br>class ListResponse&lt;T&gt; with _$ListResponse&lt;T&gt; {<br>  const factory ListResponse({<br>    int? total,<br>    List&lt;T&gt;? data,<br>    @Default(false) bool cached,<br>  }) = _ListResponse&lt;T&gt;;<br><br>  factory ListResponse.fromJson(Map&lt;String, dynamic&gt; json, T Function(Object?) fromJsonT) =&gt; _$ListResponseFromJson(json, fromJsonT);<br>}</pre><pre>// product.dart<br>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>import &#39;../dimensions/dimensions.dart&#39;;<br>import &#39;../review/review.dart&#39;;<br>import &#39;../meta/meta.dart&#39;;<br>part &#39;product.freezed.dart&#39;;<br>part &#39;product.g.dart&#39;;<br><br>@freezed<br>class Product with _$Product {<br>  const factory Product({<br>    @JsonKey(name: &#39;id&#39;) int? id,<br>    @JsonKey(name: &#39;title&#39;) String? title,<br>    @JsonKey(name: &#39;description&#39;) String? description,<br>    @JsonKey(name: &#39;category&#39;) String? category,<br>    @JsonKey(name: &#39;price&#39;) num? price,<br>    @JsonKey(name: &#39;discountPercentage&#39;) num? discountPercentage,<br>    @JsonKey(name: &#39;rating&#39;) num? rating,<br>    @JsonKey(name: &#39;stock&#39;) int? stock,<br>    @JsonKey(name: &#39;tags&#39;) List&lt;String&gt;? tags,<br>    @JsonKey(name: &#39;brand&#39;) String? brand,<br>    @JsonKey(name: &#39;sku&#39;) String? sku,<br>    @JsonKey(name: &#39;weight&#39;) int? weight,<br>    @JsonKey(name: &#39;dimensions&#39;) Dimensions? dimensions,<br>    @JsonKey(name: &#39;warrantyInformation&#39;) String? warrantyInformation,<br>    @JsonKey(name: &#39;shippingInformation&#39;) String? shippingInformation,<br>    @JsonKey(name: &#39;availabilityStatus&#39;) String? availabilityStatus,<br>    @JsonKey(name: &#39;reviews&#39;) List&lt;Review&gt;? reviews,<br>    @JsonKey(name: &#39;returnPolicy&#39;) String? returnPolicy,<br>    @JsonKey(name: &#39;minimumOrderQuantity&#39;) int? minimumOrderQuantity,<br>    @JsonKey(name: &#39;meta&#39;) Meta? meta,<br>    @JsonKey(name: &#39;images&#39;) List&lt;String&gt;? images,<br>    @JsonKey(name: &#39;thumbnail&#39;) String? thumbnail,<br>  }) = _Product;<br><br>  factory Product.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$ProductFromJson(json);<br>}</pre><p>to generate the models run in your terminal:</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><h3>2- Setup environment:</h3><p><a href="https://xflutter-cli.com/architecture/dependency-injection">Dependency Injection</a> (DI) is a design pattern that promotes loose coupling between application components by providing dependencies from an external source rather than creating them internally.</p><p>By leveraging DI frameworks, such as <a href="https://pub.dev/packages/injectable">injectable</a>, developers can ensure that components like (repositories, data-sources) are efficiently managed and reused where necessary.</p><p>We will using <a href="https://pub.dev/packages/injectable">injectable</a> package for manage dependencies like singletons like (Dio instance, Database Directory…) or temporary objects like (repositories and data-sources)</p><h4>Define environment variables:</h4><pre>abstract class AppEnvironment {<br>  /// size of chuck when fetch data with pagination<br>  int get perPage =&gt; 25;<br><br>  /// [BaseOptions.baseUrl] for [Dio]<br>  String get baseUrl;<br>}<br><br>class DevelopmentEnvironment extends AppEnvironment {<br>  @override<br>  String get baseUrl =&gt; &#39;https://development.backend.com&#39;;<br>}</pre><h4>Define Modules (for third party dependencies):</h4><pre>@module<br>abstract class AppModule {<br>  <br>  // use [Directory] for define objextbox store<br>  @preResolve<br>  @lazySingleton<br>  @Named(&#39;AppDocumentsDirectory&#39;)<br>  Future&lt;Directory&gt; provideDocumentsDirectory() =&gt; getApplicationDocumentsDirectory();<br><br>  // store chunck size, [Dio] baseUrl<br>  @lazySingleton<br>  AppEnvironment get developmentEnvironment =&gt; DevelopmentEnvironment();<br>  <br>  // provide [Dio] global instance for [Retrofit] RestClients<br>  @lazySingleton<br>  Dio provideDio(AppEnvironment environment) {<br>    final dio = Dio()<br>      ..transformer = BackgroundTransformer()<br>      ..options = BaseOptions(<br>        connectTimeout: const Duration(seconds: 60),<br>        receiveTimeout: const Duration(seconds: 60),<br>        sendTimeout: const Duration(seconds: 60),<br>        baseUrl: &#39;${environment.baseUrl}/api&#39;,<br>      );<br><br>    return dio;<br>  }<br>}</pre><h4>Configure Injectable for register dependencies:</h4><pre>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;app_injectable.config.dart&#39;; // auto generated file<br><br>/// manage dependencies<br>@InjectableInit()<br>Future&lt;void&gt; configureAppDependencies() async {<br>  await GetIt.instance.init();<br>}</pre><h4>Call Configuration at main.dart</h4><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br><br>  // initialize injectable dependencies<br>  await configureAppDependencies();<br><br>  runApp(MyApp());<br>}</pre><h3>3. Define Offline Entity:</h3><p>When defining the LocalProduct model in the context of using <a href="https://pub.dev/packages/objectbox">Objectbox</a> as a local database for Flutter:</p><pre>import &#39;package:objectbox/objectbox.dart&#39;;<br><br>@entity<br>class LocalProduct {<br>  /// The @Id annotation marks the primary key of the entity in [ObjectBox].<br>  /// This field is used to uniquely identify each entity object in the database.<br>  /// In our case, the id field is an integer, and [ObjectBox] automatically manages its value when inserting new records.<br>  /// If you set id to 0 when creating an object, ObjectBox assigns a unique value upon insertion.<br>  @Id()<br>  int id;<br>  <br>  /// The @Unique annotation ensures that the value in the productId field is unique across all entities.<br>  /// If a conflict occurs (for example, if you attempt to insert another product with the same productId),<br>  /// [ObjectBox] resolves it based on the specified onConflict strategy. In our case, ConflictStrategy.replace is used,<br>  /// meaning that if a duplicate productId is found, the existing entry is replaced with the new one.<br>  @Unique(onConflict: ConflictStrategy.replace)<br>  int? productId;<br><br>  String? name;<br>  String? description;<br><br>  /// objectbox doesn&#39;t support [num] -&gt; convert [price] to [double]<br>  double? price;<br><br>  // ... other properites<br><br>  /// one to one relation<br>  final toOneMeta = ToOne&lt;LocalMeta&gt;();<br>  final toOneDimensions = ToOne&lt;LocalDimensions&gt;();<br><br>  /// many to one relation<br>  final toManyReviews = ToMany&lt;LocalReview&gt;();<br><br>  /// using in converters<br>  LocalDimensions? dimensions;<br>  List&lt;LocalReview&gt;? reviews;<br>  LocalMeta? meta;<br><br>  LocalProduct({<br>    this.id = 0,<br>    this.productId,<br>    this.name,<br>    this.description,<br>    // ... other properites (without relations properites)<br>  });<br>}</pre><p>The <strong>@Id</strong> annotation marks the primary key of the entity in <strong>ObjectBox,</strong></p><p>This field is used to uniquely identify each entity object in the database, In our case, the id field is an integer, and <strong>ObjectBox</strong> automatically manages its value when inserting new records.</p><p>If you set id to 0 when creating an object, ObjectBox assigns a unique value upon insertion.</p><p>The <strong>@Unique</strong> annotation ensures that the value in the productId field is unique across all entities.</p><p>If a conflict occurs (for example, if you attempt to insert another product with the same productId), ObjectBox resolves it based on the specified onConflict strategy. In our case, <strong>ConflictStrategy.replace</strong> is used, meaning that if a duplicate productId is found, the existing entry is replaced with the new one.</p><p>to generate objectbox entity:</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><p>You will notice 2 new files in your app at lib directory:</p><ul><li>objectbox-model.json</li><li>objectbox.g.dart</li></ul><p>to customize the generate path edit your pubspec.yaml file:</p><pre>dependencies:<br>  # ...<br>  flutter:<br>    sdk: flutter<br><br>dev_dependencies:<br>  objectbox_generator: ^4.0.2<br>  # ...<br><br># add objectbox generator configuration<br>objectbox:<br>  # Writes objectbox-model.json and objectbox.g.dart to lib/database<br>  output_dir: data/database</pre><h3>4. Define Model Converters:</h3><p>In order to manage data from both local (<a href="https://pub.dev/packages/objectbox"><strong>Objectbox</strong></a>) and remote (<a href="https://pub.dev/packages/retrofit"><strong>Retrofit</strong></a>) data-sources, we need to create converters to map between the <strong>LocalEntity</strong> and <strong>Entity</strong> models.<br>This will allow smooth data handling between local and remote sources within the repository.</p><p>For more details about nested models:</p><ul><li><a href="https://docs.objectbox.io/relations">Relations | ObjectBox Docs</a></li><li><a href="https://docs.objectbox.io/advanced/custom-types">Custom Types | ObjectBox Docs</a></li></ul><h4>Define Converter for nested Product model:</h4><pre>import &#39;package:objectbox/objectbox.dart&#39;;<br>import &#39;package:xflutter_cli_test_application/data/models/entities/dimensions/dimensions.dart&#39;;<br><br>@entity<br>class LocalDimensions {<br>  @Id()<br>  int id = 0;<br>  double? width;<br>  double? height;<br>  double? depth;<br><br>  LocalDimensions({<br>    this.id = 0,<br>    this.width,<br>    this.height,<br>    this.depth,<br>  });<br><br>  /// convert [Dimensions] to [LocalDimensions]<br>  factory LocalDimensions.fromEntity(Dimensions dimensions) {<br>    final item = LocalDimensions(<br>      width: dimensions.width?.toDouble(),<br>      height: dimensions.height?.toDouble(),<br>      depth: dimensions.depth?.toDouble(),<br>    );<br><br>    return item;<br>  }<br><br>  /// convert [LocalDimensions] to [Dimensions]<br>  Dimensions fromLocal() =&gt; Dimensions(<br>        width: width,<br>        height: height,<br>        depth: depth,<br>      );<br>}</pre><h4>Define Converter for Product model:</h4><pre>@entity<br>class LocalProduct {<br>  // ...<br>  LocalProduct({<br>    // ...<br>  });<br><br>  /// convert [Product] to [LocalProduct]<br>  factory LocalProduct.fromEntity(Product product) {<br>    final item = LocalProduct(<br>      productId: product.id,<br>      name: product.name,<br>      description: product.description,<br>      price: product.price?.toDouble(),<br>    );<br>    <br>    // convert dimensions to localEntity before assign<br>    if (product.dimensions != null) {<br>      item.toOneDimensions.target = LocalDimensions.fromEntity(product.dimensions!);<br>    }<br>    <br>    // convert meta to localEntity before assign<br>    if (product.meta != null) {<br>      item.toOneMeta.target = LocalMeta.fromEntity(product.meta!);<br>    }<br><br>     // convert reviews to localEntity before assign<br>    if (product.reviews != null) {<br>      item.toManyReviews.addAll(product.reviews?.map((e) =&gt; LocalReview.fromEntity(e)) ?? []);<br>    }<br><br>    return item;<br>  }<br><br>  /// convert [LocalProduct] to [Product]<br>  Product fromLocal() =&gt; Product(<br>    id: productId,<br>    name: name,<br>    description: description,<br>    price: price,<br>    meta: toOneMeta.target?.fromLocal(),<br>    dimensions: toOneDimensions.target?.fromLocal(),<br>    reviews: toManyReviews.map((e) =&gt; e.fromLocal()).toList(),<br>  );<br>}</pre><h3>5. Define Objectbox Store:</h3><p>Objectbox will automatically generates the localStore after generating:</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><p>But if we want to initialize objectBox store with custom configurations like (directory path) we can define our custom store:</p><pre>import &#39;dart:io&#39;;<br>import &#39;objectbox.g.dart&#39;; // auto generated file<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;package:path/path.dart&#39; show join;<br><br>@lazySingleton<br>class ObjectBoxAppStore {<br>  final Directory directory;<br>  ObjectBoxAppStore(@Named(&#39;AppDocumentsDirectory&#39;) this.directory);<br><br>  String get _version =&gt; &#39;v1&#39;;<br><br>  /// open new objectbox [Store] with specific [_version]<br>  Store openStore() =&gt; Store(getObjectBoxModel(), directory: join(directory.path, &#39;app_objectbox_$_version&#39;));<br>}</pre><p>here we defined a global instance for objectbox store with version and directory path, we will use this in our <strong>Local Data-Source</strong></p><h3>6. Define Local Data-Source:</h3><p>When creating a local data source for <a href="https://pub.dev/packages/objectbox">Objectbox</a>, the main responsibility of this layer is performing database operations by managing CRUD (Create, Read, Update, Delete) operations for your data models — in this case, the LocalProduct model.<br>Below is a step-by-step explanation of how to define an Objectbox local data source for managing LocalProduct operations.</p><pre>class LocalProductQueryParameters {<br>  final int? id;<br><br>  const LocalProductQueryParameters({this.id});<br>}<br><br>class LocalProductsListQueryParameters {<br>  final int? page;<br>  final int? perPage;<br><br>  const LocalProductsListQueryParameters({this.page, this.perPage});<br>}</pre><pre>import &#39;queries/local_products_query_parameters.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/local/product/local_product.dart&#39;;<br><br>abstract class ProductsLocalDataSource {<br>  /// find [LocalProduct] from local-database<br>  Future&lt;LocalProduct?&gt; findOne(LocalProductQueryParameters queryParameters);<br><br>  /// fetch cached [LocalProduct] list from local-database<br>  Future&lt;List&lt;LocalProduct&gt;&gt; findAll(LocalProductsListQueryParameters queryParameters);<br><br>  /// add/update [LocalProduct] into local-database<br>  Future&lt;void&gt; insert(LocalProduct data);<br><br>  /// save list of [LocalProduct] in local-database<br>  Future&lt;void&gt; insertAll(Iterable&lt;LocalProduct&gt; data);<br><br>  /// delete [LocalProduct] from local-database<br>  Future&lt;int&gt; delete(int? id);<br><br>  /// count all [LocalProduct] items in local-database<br>  Future&lt;int&gt; count();<br>}</pre><h4>Define data source implementation:</h4><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;queries/local_products_query_parameters.dart&#39;;<br>import &#39;products_local_data_source.dart&#39;;<br>import &#39;package:xflutter_cli/data/database/app_store.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/local/product/local_product.dart&#39;;<br>import &#39;package:xflutter_cli/data/database/objectbox.g.dart&#39;;<br><br>@Injectable(as: ProductsLocalDataSource)<br>class ProductsLocalDataSourceImpl implements ProductsLocalDataSource {<br>  final ObjectBoxAppStore _appStore;<br>  ProductsLocalDataSourceImpl(this._appStore);<br><br>  @override<br>  Future&lt;void&gt; insert(LocalProduct data) =&gt; insertAll([data]);<br><br>  @override<br>  Future&lt;void&gt; insertAll(Iterable&lt;LocalProduct&gt; data) async {<br>    final store = _appStore.openStore();<br>    // open Transaction<br>    await store.runInTransactionAsync&lt;void, List&lt;LocalProduct&gt;&gt;(<br>      TxMode.write,<br>      (Store store, List&lt;LocalProduct&gt; parameter) {<br>        try {<br>          final box = store.box&lt;LocalProduct&gt;();<br><br>          // find existing items for update<br>          final ids = parameter.map((e) =&gt; e.productId!).toList();<br>          final query = box.query(LocalProduct_.productId.oneOf(ids)).build();<br>          final items = query.find();<br><br>          // clean up resources<br>          query.close();<br><br>          // assign ids to objects<br>          for (var item in items) {<br>            final index = parameter.indexWhere((e) =&gt; e.productId == item.productId);<br>            parameter[index].id = item.id;<br>          }<br><br>          // insert new data, and update existing data<br>          box.putMany(parameter);<br>        } catch (error) {<br>          debugPrint(error.toString());<br>        }<br>      },<br>      data.toList(),<br>    );<br><br>    // clean up resources<br>    store.close();<br>  }<br><br>  @override<br>  Future&lt;LocalProduct?&gt; findOne(LocalProductQueryParameters queryParameters) async {<br>    if (queryParameters.id == null) return null;<br>    final store = _appStore.openStore();<br>    // open Transaction<br>    final result = await store.runInTransactionAsync&lt;LocalProduct?, LocalProductQueryParameters&gt;(<br>      TxMode.read,<br>      (Store store, LocalProductQueryParameters parameter) {<br>        try {<br>          final box = store.box&lt;LocalProduct&gt;();<br><br>          // query builder for find item with filters<br>          final query = box.query().build();<br>          if (parameter.id != null) {<br>            // filter on localProduct productId<br>            query.param(LocalProduct_.productId).value = parameter.id!;<br>          }<br><br>          final item = query.findFirst();<br><br>          // mapping item<br>          if (item != null) _mappingItem(item);<br><br>          // clean up resources<br>          query.close();<br><br>          return item;<br>        } catch (error) {<br>          debugPrint(error.toString());<br>          return null;<br>        }<br>      },<br>      queryParameters,<br>    );<br>    store.close();<br>    return result;<br>  }<br><br>  @override<br>  Future&lt;List&lt;LocalProduct&gt;&gt; findAll(LocalProductsListQueryParameters queryParameters) async {<br>    final store = _appStore.openStore();<br>    // open Transaction<br>    final result = await store.runInTransactionAsync&lt;List&lt;LocalProduct&gt;, LocalProductsListQueryParameters&gt;(<br>      TxMode.read,<br>      (Store store, LocalProductsListQueryParameters parameter) {<br>        try {<br>          final box = store.box&lt;LocalProduct&gt;();<br>          final query = box.query().build();<br><br>          // add pagination<br>          final page = parameter.page;<br>          final perPage = parameter.perPage;<br>          if (page != null &amp;&amp; perPage != null) {<br>            query.offset = (perPage * page) - perPage;<br>            query.limit = perPage;<br>          }<br><br>          // find items<br>          final items = query.find();<br><br>          // mapping items<br>          for (var item in items) {<br>            _mappingItem(item);<br>          }<br><br>          // clean up resources<br>          query.close();<br><br>          return items;<br>        } catch (error) {<br>          debugPrint(error.toString());<br>          return [];<br>        }<br>      },<br>      queryParameters,<br>    );<br><br>    // clean up resources<br>    store.close();<br>    <br>    return result;<br>  }<br><br>  @override<br>  Future&lt;int&gt; delete(int? id) async {<br>    if (id == null) return 0;<br>    final store = _appStore.openStore();<br>    // open Transaction<br>    final result = await store.runInTransactionAsync&lt;int, int&gt;(<br>      TxMode.read,<br>      (Store store, int parameter) {<br>        try {<br>          final box = store.box&lt;LocalProduct&gt;();<br><br>          // filter item<br>          final query = box.query(LocalProduct_.productId.equals(id)).build();<br><br>          // remove item<br>          final result = query.remove();<br><br>          // clean up resources<br>          query.close();<br><br>          return result;<br>        } catch (error) {<br>          debugPrint(error.toString());<br>          return 0;<br>        }<br>      },<br>      id,<br>    );<br><br>    // clean up resources<br>    store.close();<br>    <br>    return result;<br>  }<br><br>  @override<br>  Future&lt;int&gt; count() async {<br>    final store = _appStore.openStore();<br>    <br>    // open Transaction<br>    final result = await store.runInTransactionAsync&lt;int, dynamic&gt;(<br>      TxMode.read,<br>      (Store store, _) {<br>        try {<br>          final box = store.box&lt;LocalProduct&gt;();<br>          final query = box.query().build();<br><br>          // count items<br>          final count = query.count();<br><br>          // clean up resources<br>          query.close();<br><br>          return count;<br>        } catch (error) {<br>          debugPrint(error.toString());<br>          return 0;<br>        }<br>      },<br>      null,<br>    );<br><br>    // clean up resources<br>    store.close();<br>    <br>    return result;<br>  }<br><br>  /// objectbox require opened [Store] for mapping relations, embedded objects,<br>  ///<br>  /// mapping [LocalProduct] for access properties outside store<br>  void _mappingItem(LocalProduct item) {<br>    item.dimensions = item.toOneDimensions.target;<br>    item.meta = item.toOneMeta.target;<br>    item.reviews = item.toManyReviews.toList();<br>  }<br>}</pre><p>Here we implement all <strong>LocalProduct</strong> operations with objectBox.</p><p>All operations will be executed in isolated thread to get better performance.</p><p>This will cache all products which will be fetched from <strong>Remote Data-Source</strong></p><h3>7. Define Remote Data-Source</h3><p>In modern applications, integrating with remote servers via APIs is crucial for functionalities such as fetching data, submitting forms, and synchronizing information.<br>In Flutter, the <a href="https://pub.dev/packages/retrofit">Retrofit</a> package simplifies this process by providing a declarative approach to make HTTP requests, ensuring your code is clean, type-safe, and easy to maintain.<br>Below, we will walk through the setup of a remote data source using <a href="https://pub.dev/packages/retrofit">Retrofit</a> specifically tailored for a Product model.</p><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:retrofit/retrofit.dart&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/entities/product/product.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/responses/base_response/base_response.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/responses/list_response/list_response.dart&#39;;<br><br>part &#39;products_remote_data_source.g.dart&#39;;<br><br>@injectable<br>@RestApi()<br>abstract class ProductsRemoteDataSource {<br>  @factoryMethod<br>  factory ProductsRemoteDataSource(Dio dio) = _ProductsRemoteDataSource;<br><br>  @GET(&#39;/shop/products&#39;)<br>  Future&lt;BaseResponse&lt;ListResponse&lt;Product&gt;&gt;&gt; findAll({<br>    @Query(&#39;page&#39;) required int page,<br>    @Query(&#39;per_page&#39;) required int perPage,<br>  });<br><br>  @GET(&#39;/shop/products/{id}&#39;)<br>  Future&lt;BaseResponse&lt;Product&gt;&gt; findOne({<br>    @Path(&#39;id&#39;) required int? id,<br>  });<br>}</pre><h3>8. Exposing Data by Repository</h3><p>Repositories are a fundamental part of app architecture, acting as an intermediary between the data layer and the rest of the application. In Flutter, repositories streamline how data is fetched, stored, and modified.<br>They provide a single access point for data, whether it comes from remote APIs or local databases, ensuring that business logic is consistently applied across your app.</p><p>For make device fetch remote data only when device connected to network:</p><pre>import &#39;package:connectivity_plus/connectivity_plus.dart&#39;;<br><br>/// check if device is connected to network<br>Future&lt;bool&gt; isConnectingToInternet() async {<br>  final connectivityResult = await Connectivity().checkConnectivity();<br>  return !connectivityResult.contains(ConnectivityResult.none);<br>}</pre><p><strong>async*</strong> functions return a <strong>Stream</strong> and are used to emit multiple asynchronous values over time.</p><p><strong>yield</strong> is used in <strong>async*</strong> functions to emit values.</p><pre>import &#39;dart:async&#39;;<br>import &#39;package:xflutter_cli/data/models/entities/product/product.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/responses/base_response/base_response.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/responses/list_response/list_response.dart&#39;;<br><br>abstract class ProductsRepository {<br>  Stream&lt;BaseResponse&lt;ListResponse&lt;Product&gt;&gt;&gt; findAll(int page);<br>}</pre><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;dart:async&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;products_repository.dart&#39;;<br>import &#39;package:xflutter_cli_test_application/data/models/entities/product/product.dart&#39;;<br>import &#39;package:xflutter_cli_test_application/data/data_sources/remote/products/products_remote_data_source.dart&#39;;<br>import &#39;../base_repository.dart&#39;;<br>import &#39;package:xflutter_cli/extensions/di_extension.dart&#39;;<br>import &#39;package:xflutter_cli/environments/environments.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/responses/base_response/base_response.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/responses/list_response/list_response.dart&#39;;<br>import &#39;package:xflutter_cli/data/data_sources/local/products/products_local_data_source.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/local/product/local_product.dart&#39;;<br>import &#39;package:xflutter_cli/data/data_sources/local/products/queries/local_products_query_parameters.dart&#39;;<br><br>@Injectable(as: ProductsRepository)<br>class ProductsRepositoryImpl extends BaseRepository implements ProductsRepository {<br>  final ProductsRemoteDataSource _remoteDataSource;<br>  final ProductsLocalDataSource _localDataSource;<br><br>  ProductsRepositoryImpl(this._remoteDataSource, this._localDataSource);<br><br>  @override<br>  Stream&lt;BaseResponse&lt;ListResponse&lt;Product&gt;&gt;&gt; findAll(int page) async* {<br>    final perPage = getIt&lt;AppEnvironment&gt;().perPage;<br>    <br>    // get cached data from local dataSource<br>    final queryParams = LocalProductsListQueryParameters(page: page, perPage: perPage);<br>    final cached = await _localDataSource.findAll(queryParams);<br>    if (cached.isNotEmpty) {<br>      // map localProducts to products<br>      final products = cached.map((e) =&gt; e.fromLocal()).toList();<br><br>      // emit cached data<br>      yield BaseResponse(<br>        success: true,<br>        data: ListResponse(data: products, total: null, cached: true),<br>      );<br>    }<br><br>    // check network connection<br>    if (await isConnectingToInternet()) {<br>      // fetch data from server<br>      final response = await _remoteDataSource.findAll(page: page, perPage: perPage);<br><br>      // emit fetched data<br>      yield response;<br><br>      <br>      if (response.data?.data != null) {<br>        // map fetched products to localProducts<br>        final products = response.data!.data!.map((e) =&gt; LocalProduct.fromEntity(e));<br><br>        // insert/update fetched data into cache<br>        await _localDataSource.insertAll(products);<br>      }<br>    }<br>  }<br>}</pre><h3>9. Define Paging Controller:</h3><p>The PagingController is responsible for holding and fetching new chunks of data when the user scrolls. It is designed to isolate the pagination logic from the UI, making it reusable across different screens.</p><h4>Advantages of Using PagingController:</h4><ol><li><strong>Separation of Concerns</strong>: By keeping the pagination logic in the controller, the UI remains focused on presenting the data and remains decoupled from the data-fetching logic. This makes the code more maintainable and easier to test.</li><li><strong>Isolated and Reusable</strong>: The PagingController can be reused across different screens or components that need pagination, such as a product list, a list of favorite items, or a list of orders. This enhances code reusability, keeping business logic centralized and separated from UI components.</li><li><strong>State Management</strong>: The controller manages the state of data fetching, like loading more pages, retrying failed requests, and handling refresh events. This reduces boilerplate code for managing these states in the UI.</li></ol><pre>import &#39;dart:async&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:animated_infinite_scroll_pagination/animated_infinite_scroll_pagination.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/entities/product/product.dart&#39;;<br>import &#39;package:xflutter_cli/data/repositories/products/products_repository.dart&#39;;<br><br>@injectable<br>class ProductsPagingController with AnimatedInfinitePaginationController&lt;Product&gt; {<br>  final ProductsRepository _repository;<br>  ProductsPagingController(this._repository);<br><br>  /// decide whether two object represent the same Item<br>  @override<br>  bool areItemsTheSame(Product oldItem, Product newItem) {<br>    return oldItem.id == newItem.id;<br>  }<br><br>  /// fetch data from repository and emit new state<br>  ///<br>  /// set total items count -&gt; stop loading on last page<br>  /// <br>  /// use [emitState] to reflect new [PaginationState] to UI<br>  @override<br>  Future&lt;void&gt; fetchData(int page) async {<br>    // emit loading<br>    emitState(const PaginationLoadingState());<br><br>    // fetch data from server<br>    try {<br>      await for (final response in _repository.findAll(page)) {<br>        final result = response.data;<br>        if (result?.data != null) {<br>          // emit fetched data<br>          emitState(PaginationSuccessState(result!.data!.toList(), cached: result.cached));<br><br>          // tell the controller the total of items,<br>          // this will stop loading more data when last data-chunk is loaded.<br>          setTotal(result.total ?? 0);<br>        } else {<br>          // emit error<br>          emitState(const PaginationErrorState());<br>        }<br>      }<br>    } catch (error) {<br>      // emit error<br>      emitState(const PaginationErrorState());<br>      if (kDebugMode) print(error);<br>    }<br>  }<br>}</pre><h3>10. Integration with UI:</h3><p>The integration of the PagingController with the UI happens through the <strong>AnimatedInfiniteScrollView</strong> widget from the (<a href="https://pub.dev/packages/animated_infinite_scroll_pagination">animated_infinite_scroll_pagination</a>) package,</p><p>which handles displaying paginated data efficiently while managing loading indicators, errors, and refresh events.<br>This widget is designed to work seamlessly with the PagingController to provide a fluid and responsive user experience for lists with infinite scroll functionality.</p><h4>Role of AnimatedInfiniteScrollView:</h4><ol><li><strong>Rendering Paginated Data</strong>: The <strong>AnimatedInfiniteScrollView</strong> listens to the data managed by the PagingController and dynamically displays items as they are fetched. As new data is loaded, it automatically updates the UI.</li><li><strong>Handling User Interaction</strong>: As the user scrolls to the bottom of the list, the scroll view detects the scroll offset and triggers the PagingController to fetch the next chunk of data. This keeps the experience seamless as more data is loaded in the background.</li><li><strong>Loading and Error States</strong>: While fetching data, the scroll view shows loading indicators or placeholders, ensuring that users understand that new content is being loaded. If any error occurs during the data-fetching process, an error widget can be displayed, offering retry options.</li><li><strong>Pull-to-Refresh</strong>: The <strong>AnimatedInfiniteScrollView</strong> supports the common pull-to-refresh gesture, which allows users to refresh the content from the beginning of the list. This triggers the PagingController to clear the current data and fetch a new set of data starting from the first page.</li></ol><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;mobile/products_list_mobile_screen.dart&#39;;<br>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:xflutter_cli/data/models/entities/product/product.dart&#39;;<br><br>@RoutePage(name: &#39;productsList&#39;)<br>class ProductsListScreen extends StatefulWidget {<br>  const ProductsListScreen({super.key});<br><br>  @override<br>  State&lt;ProductsListScreen&gt; createState() =&gt; _ProductsListScreenState();<br>}<br><br>class _ProductsListScreenState extends State&lt;ProductsListScreen&gt; {<br>  // get injected instance of pagingController<br>  final pagingController = GetIt.instance&lt;ProductsPagingController&gt;();<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    // fetch first chuck of data<br>    // this will be trigger for pagingController to start fetching data<br>    // fetch next chuck of data on scroll events<br>    // will be handled from pagingController side<br>    pagingController.fetchNewChunk();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: SafeArea(<br>        child: AnimatedInfiniteScrollView&lt;Product&gt;(<br>          // Link to PagingController<br>          controller: pagingController,<br><br>          options: AnimatedInfinitePaginationOptions(<br>            // Displayed when loading<br>            loadingWidget: const CircularProgressIndicator.adaptive(),<br>          <br>            // Displayed on error<br>            errorWidget: const Center(child: Text(&#39;An error occurred&#39;)),<br>            <br>            // Build the UI for each product item<br>            itemBuilder: (BuildContext context, Product product, int index) {<br>              return ListTile(<br>                title: Text(product.name!),<br>                subtitle: Text(product.description!),<br>              );<br>            },<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Full Example:</h3><p><a href="https://github.com/aghiadodeh/xflutter_cli/tree/v2.5.0/xflutter_cli_modules_application/lib/modules/products/presentation/screens/products_list">xflutter_cli/xflutter_cli_modules_application/lib/modules/products/presentation/screens/products_list at v2.5.0 · aghiadodeh/xflutter_cli</a></p><h4>Backend Project:</h4><p><a href="https://github.com/aghiadodeh/nodejs-test">GitHub - aghiadodeh/nodejs-test: NodeJs Simple Server to test dummy json apis</a></p><pre>npm install<br>npm start</pre><h3>Data Layer explaining:</h3><p><a href="https://xflutter-cli.com/architecture/data-layer/intro">XFlutter CLI</a></p><h3>Improve Productivity:</h3><p><a href="https://xflutter-cli.com/cli/make/crud">XFlutter CLI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d5937746828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter State Management with Dependency Injection]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-state-management-with-dependency-injection-f016d51515ce?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/f016d51515ce</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[scopes]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 11:57:31 GMT</pubDate>
            <atom:updated>2024-11-28T08:37:57.894Z</atom:updated>
            <content:encoded><![CDATA[<p>State management is one of the most critical aspects of developing applications in Flutter. In essence, state refers to the information required by an app to represent its UI at any given moment.</p><p>For example, in a login screen, the state might include whether the user is authenticated, the email and password they input, and any validation errors.<br>Managing this state properly is essential for making sure that the UI remains consistent with the data, responds correctly to user input, and handles events such as network responses or system updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*aAItuD9mFTq0VVP_FIYOBA.png" /><figcaption>UI Layer</figcaption></figure><p>Flutter offers a variety of solutions for managing state. For simple cases, the <strong>setState()</strong> function can update the UI directly. However, as apps grow more complex,<br>this basic approach becomes hard to maintain, leading developers to use patterns like <a href="https://pub.dev/packages/provider">Provider</a>, <a href="https://pub.dev/packages/riverpod">Riverpod</a>, or <a href="https://pub.dev/packages/bloc">BLoC</a> (Business Logic Component).<br>Each state management solution helps organize the logic that drives the UI and ensures that the app reacts efficiently to changes. The primary goal is to make it easy to maintain data consistency while decoupling business logic from UI code, which can become quite entangled otherwise.</p><p>Now that we’ve covered the general concept of Flutter state management,<br>let’s dive into a specific state management approach using <strong>ViewModel</strong> combined <a href="https://xflutter-cli.com/components/ui/di/lifecycle-owner"><strong>LifecycleOwner</strong></a> and <a href="https://pub.dev/packages/flutterx_live_data"><strong>LiveData</strong></a> as the observable data holder. This approach offers a structured, scalable, and efficient way of managing state in Flutter apps.</p><h3>Using ViewModel for State Management in Flutter</h3><p>One efficient way to organize and manage state in Flutter applications is to implement a State Holder (ViewModel).<br>This is a centralized class responsible for managing business logic and providing observable data for the UI to render.</p><p>Here, we’ll walk through how ViewModel, <a href="https://xflutter-cli.com/components/ui/di/lifecycle-owner">LifecycleOwner</a>, and <a href="https://pub.dev/packages/flutterx_live_data">LiveData</a> work together to create a clean, maintainable architecture for managing state.</p><h3>1. UI Layer Architecture:</h3><p>In Flutter, the term UI encompasses the various UI components, such as widgets, that are responsible for displaying data, regardless of the specific mechanisms used.</p><h4>The UI layer is further divided into two sub-layers:</h4><ol><li><strong>UI Elements</strong>: These are the widgets that render the data on the screen, such as Text, Image, Input, or any other StatelessWidget or StatefulWidget.</li><li><strong>State Holders (ViewModels)</strong>: These include tools like BLoC, Provider, or similar architectures that hold the data, expose it to the UI elements, and handle UI events. They serve as the bridge between the data and the UI, ensuring that any changes in the application data are reflected in the UI elements.</li></ol><figure><img alt="Separation of UI layer" src="https://cdn-images-1.medium.com/max/1006/1*IQEOU-G3mgBH8THkHg8X7w.png" /><figcaption>Separation of Ui layers</figcaption></figure><h3>2. Defining the UI State:</h3><p>In Flutter, defining a clear UI state is crucial for managing and rendering the interface.<br>When using <a href="https://pub.dev/packages/flutterx_live_data">Live Data</a>, you can represent your state, which holds all the necessary data for the UI. Here’s how to structure it:</p><pre>// define model<br>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>part &#39;product.freezed.dart&#39;;<br>part &#39;product.g.dart&#39;;<br><br>@freezed<br>class Product with _$Product {<br>  const factory Product({<br>    required String name,<br>    required String description,<br>    required num price,<br>  }) = _Product;<br>}</pre><p>And let’s define our <em>Observable Data Holder</em>:</p><pre>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;package:xflutter_cli_app/models/data/product/product.dart&#39;;<br><br>// Initial Product State<br>const _initialProductValue = Product(<br>  name: &#39;Apple&#39;,<br>  description: &#39;Fresh and crisp apples.&#39;,<br>  price: 50.0,<br>);<br><br>class ProductsViewModel {<br>  // Product observable data holder<br>  final product = MutableLiveData&lt;Product&gt;(value: _initialProductValue);<br>}</pre><p>Product <em>MutableLiveData</em> will allow you to display your data interactively using UI elements.</p><h3>3. Unidirectional Data Flow (UDF):</h3><p>Interactions in the UI can benefit from a mediator that handles the logic for each event, processing them and transforming the underlying data to generate the UI state.<br>While this logic can reside within the UI itself, this approach can quickly become overwhelming.<br>The UI ends up taking on multiple roles — data ownership, transformation, and production — leading to tightly coupled, complex code that’s difficult to maintain and test.<br>To keep things manageable, it’s better to reduce the UI’s responsibilities. Unless the UI state is very simple, the UI should focus solely on consuming and displaying the state, leaving the rest to a dedicated mediator.<a href="https://xflutter-cli.com/architecture/ui-layer/intro#udf"><strong>Unidirectional Data Flow</strong></a> models the process of state production by clearly separating where state changes are initiated, where they are transformed, and where they are finally consumed.<br>This structure allows the UI to focus solely on its intended role: displaying information by observing state changes and communicating user actions back to the ViewModel by events.</p><h4>Update Data with UDF from UI elements side:</h4><pre>// ❌ without using UDF<br>@override<br>Widget build(BuildContext context) {<br>  return Scaffold(<br>    body: SafeArea(<br>      child: InkWell(<br>        child: Text(&#39;Update Product Name&#39;),<br>        onTap: () {<br>          // update product name directly from UI element<br>          final Product data = viewModel.product.value;<br>          viewModel.product.postValue(data.copyWith(name: &#39;new name ${DateTime.now()}&#39;));<br>        },<br>      ),<br>    ),<br>  );<br>}</pre><pre>// ✅ using UDF<br>@override<br>Widget build(BuildContext context) {<br>  return Scaffold(<br>    body: SafeArea(<br>      child: InkWell(<br>        child: Text(&quot;Update Product Name&quot;),<br>        onTap: () {<br>          // send event to state-holder for update<br>          viewModel.updateProductName(&#39;new name ${DateTime.now()}&#39;);<br>        },<br>      ),<br>    ),<br>  );<br>}</pre><h4>Update Data with UDF from State-Holder side:</h4><pre>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;package:xflutter_cli_app/models/data/product/product.dart&#39;;<br><br>class ProductsViewModel {<br>  // ❌ without using UDF<br>  final product = MutableLiveData&lt;Product&gt;(value: _initialProductValue);<br>}</pre><pre>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;package:xflutter_cli_app/models/data/product/product.dart&#39;;<br><br>class ProductsViewModel {<br>  // ✅ using UDF<br>  /// prevent update values outside viewModel<br>  /// [LiveData] is an observable data carrier with no update capability value, <br>  /// only [MutableLiveData] can be updated.<br>  final _product = MutableLiveData&lt;Product&gt;(value: _initialProductValue);<br>  LiveData&lt;Product&gt; get product =&gt; _product;<br><br>  /// handle update [Product] name event<br>  void updateProductName(String productName) {<br>    final Product data = _product.value;<br>    _product.postValue(data.copyWith(name: productName));<br>  }<br>}</pre><h3>4. Implementing UI:</h3><p>Once your UI state is defined and observable, the final step is to build UI elements that can consume this state. By observing <em>MutableLiveData</em>,<br>you can make your widgets react to data changes seamlessly. <a href="https://pub.dev/packages/flutterx_live_data">flutterx_live_data</a> provides an easy way to listen for observable data changes by:</p><ol><li><strong>LiveData Builder</strong>: update some UI element based on new data.</li><li><strong>Register Observer</strong>: listen for data changes outside of your UI element tree.</li></ol><h4>* Using LiveDataBuilder:</h4><p>Update UI elements with latest changes:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;package:xflutter_cli_app/models/data/product/product.dart&#39;;<br><br>class ProductScreen extends StatefulWidget {<br>  const ProductScreen({super.key});<br><br>  @override<br>  State&lt;ProductScreen&gt; createState() =&gt; _ProductScreenState();<br>}<br><br>class _ProductScreenState extends State&lt;ProductScreen&gt; {<br>  final viewModel = ProductsViewModel();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: SafeArea(<br>        child: Column(<br>          children: [<br>            const Text(&#39;Product Screen&#39;),<br><br>            LiveDataBuilder&lt;Product&gt;(<br>              data: viewModel.product,<br>              builder: (BuildContext context, Product product) {<br>                // re-built every time viewModel.product value changed<br>                return Column(<br>                  children: [<br>                    Text(product.name),<br>                    Text(&#39;${product.price} USD&#39;),<br>                    Text(product.description),<br>                  ],<br>                );<br>              },<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h4>* Using Register Observers:</h4><p>Listen for changes outside the UI tree:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;package:xflutter_cli_app/models/data/product/product.dart&#39;;<br><br>class ProductScreen extends StatefulWidget {<br>  const ProductScreen({super.key});<br><br>  @override<br>  State&lt;ProductScreen&gt; createState() =&gt; _ProductScreenState();<br>}<br><br>class _ProductScreenState extends State&lt;ProductScreen&gt; with ObserverMixin {<br>  final viewModel = ProductsViewModel();<br><br>  @override<br>  void initState() {<br>    doRegister(); // start observing changes<br>    super.initState();<br>  }<br><br>  @override<br>  FutureOr&lt;void&gt; registerObservers() {<br>    // listen for product changes<br>    viewModel.product.observe(this, (Product value) {<br>      // show snackBar for each product update<br>      ScaffoldMessenger.of(context)<br>        ..hideCurrentSnackBar()<br>        ..showSnackBar(<br>            SnackBar(content: Text(&#39;Product ${value.name} updated!!&#39;)),<br>        );<br>    });<br>  }<br><br>  @override<br>  void dispose() {<br>    doUnregister(); // stop observing changes<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: SafeArea(<br>        child: Column(<br>          children: [<br>            // ...<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>5. State Management with Dependency Injection:</h3><p><a href="https://xflutter-cli.com/architecture/dependency-injection">Dependency Injection</a> (DI) is a design pattern that promotes loose coupling between application components by providing dependencies from an external source rather than creating them internally.</p><p>By leveraging DI frameworks, such as <a href="https://pub.dev/packages/injectable">injectable</a>, developers can ensure that state management components like ViewModels are efficiently managed and reused where necessary.</p><pre>import &#39;package:injectable/injectable.dart&#39;;<br><br>@injectable<br>class ProductsViewModel {<br>  final ProductRepository _repository;<br>  ProductsViewModel(this._repository);<br>}<br><br>@injectable<br>class ProductRepository {<br>  // ...<br>}</pre><p>In this example, @injectable tells <a href="https://pub.dev/packages/injectable">injectable</a> to automatically register the <em>ProductsViewModel</em> with <a href="https://pub.dev/packages/get_it">get_it</a>. The constructor’s parameters (ProductRepository) are automatically resolved, as long as these dependencies are also registered.</p><p>Registered instances will be accessible after <a href="https://pub.dev/packages/injectable_generator">injectable_generator</a> running by:</p><pre>dart run build_runner build --delete-conflicting-outputs</pre><h4>Access the registered viewModel from UI elements:</h4><pre>import &#39;package:get_it/get_it.dart&#39;;<br><br>class ProductScreen extends StatefulWidget {<br>  const ProductScreen({super.key});<br><br>  @override<br>  State&lt;ProductScreen&gt; createState() =&gt; _ProductScreenState();<br>}<br><br>class _ProductScreenState extends State&lt;ProductScreen&gt; with ObserverMixin {<br>  final ProductsViewModel viewModel = GetIt.instance&lt;ProductsViewModel&gt;();<br>}</pre><h3>Difference Between @injectable and @singleton:</h3><p>While both @injectable and @singleton annotations help with automatic registration, they serve different purposes, particularly in how they manage object lifecycles.</p><h4>@injectable: Default Behavior</h4><ul><li><strong>Instance Creation</strong>: By default, classes annotated with @injectable are created every time they are requested.<br>This means that the same class can have multiple instances throughout the app.</li><li><strong>Use Case</strong>: This is useful for classes that should not be reused globally,<br>such as classes with short lifecycles or objects that need to be created multiple times (e.g., temporary objects for specific screens).</li></ul><h4>@singleton: Singleton Behavior</h4><ul><li><strong>Global Instance</strong>: When you use @singleton, the annotated class is created once and shared throughout the app.<br>This means that every time the class is requested, the same instance is returned.</li><li><strong>Memory Efficiency</strong>: Singletons are ideal for services that should be reused globally, such as repositories, database connections, or network services.<br>This ensures that the service is only initialized once, avoiding unnecessary memory usage.</li></ul><h4>Using Scopes with @singleton: Memory Management and Cleanup:</h4><p><strong>Scopes</strong> allow registration of related dependencies in a different scope, so they can be initialized only when needed and disposed of when they’re not.</p><p>One of the most efficient strategies for managing memory in Flutter applications is to <strong>mix singleton usage with temporary objects</strong>, and this is where scoped singletons come into play.</p><p><strong>Scoped singletons</strong> provide a mechanism to share the same instance of a class (like a repository) across multiple screens or processes, while ensuring it is properly cleaned up when no longer needed.</p><h4>Case Study:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*PtYGW8NHvZseIZHqDK1Erw.png" /></figure><p>In a login form, the ViewModel can manage validation, handle authentication, and expose a loading state, while the UI just observes those states and displays them.</p><h4>Implementing Scoped Singletons:</h4><p>The injectable package builds on top of <a href="https://pub.dev/packages/get_it">get_it</a>, automating the process of registering dependencies and providing better support for managing scoped dependencies. It uses annotations and code generation to register services, repositories, and view-models, reducing boilerplate and improving maintainability.</p><pre>// di.dart<br>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;app_injectable.config.dart&#39;; // auto generated<br><br>/// register all injectable dependencies<br>@InjectableInit()<br>Future&lt;void&gt; configureAppDependencies() =&gt; GetIt.instance.init();</pre><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br><br>  // initialize injectable dependencies<br>  await configureAppDependencies();<br><br>  runApp(MyApp());<br>}</pre><p>Define the scope for state-holder:</p><pre>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;package:reactive_forms/reactive_forms.dart&#39;;<br>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;package:xflutter_cli/modules/authentication/data/repositories/authentication/authentication_repository.dart&#39;;<br>import &#39;package:xflutter_cli/modules/authentication/data/models/requests/login_request/login_request.dart&#39;;<br><br>// replace @injectable with @LazySingleton with scope name<br>@LazySingleton(scope: &#39;products&#39;)<br>class LoginViewModel {<br>  /// display progress widget<br>  final _loading = false.liveData;<br>  LiveData&lt;bool&gt; get loading =&gt; _loading;<br><br>  /// [LiveEvent] for emit login result to UI (navigate on success)<br>  final _result = LiveEvent&lt;LoginResponse&gt;();<br>  ObservableData&lt;LoginResponse&gt; get result =&gt; _result;<br><br>  /// auth Repository<br>  final AuthenticationRepository _authenticationRepository;<br><br>  LoginViewModel(this._authenticationRepository);<br><br>  /// login formGroup<br>  final loginForm = FormGroup({<br>    &#39;email&#39;: FormControl&lt;String&gt;(<br>      validators: [<br>        Validators.email,<br>        Validators.required,<br>      ],<br>    ),<br>    &#39;password&#39;: FormControl&lt;String&gt;(<br>      validators: [<br>        Validators.required,<br>        Validators.minLength(8),<br>      ],<br>    ),<br>  });<br><br><br>  /// update [_loading] with new [value]<br>  void setLoading(bool value) {<br>    _loading.postValue(value);<br>  }<br><br>  /// send credentials to server for login<br>  void submit() {<br>    // display loading<br>    setLoading(true);<br>    <br>    // send http request<br>    final Map&lt;String, dynamic&gt; credentials = params.loginForm.value;<br>    final request = LoginRequest.from(credentials);<br>    final response = await _authenticationRepository.login(request);<br>    <br>    if (response != null) {<br>      // emit login response to UI for handling (navigate, display message)<br>      setResult(response!);<br>    } else {<br>      // handle error<br>    }<br>     <br>    // hide loading<br>    setLoading(false);<br>  }<br><br>  /// emit new value for loginResponse result<br>  void setResult(LoginResponse value) {<br>    _result.send(value);<br>  }<br>}</pre><pre>// login_screen.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;mobile/login_mobile_screen.dart&#39;;<br>import &#39;tablet/login_tablet_screen.dart&#39;;<br>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:injectable/injectable.dart&#39;;<br>import &#39;package:flutterx_live_data/flutterx_live_data.dart&#39;;<br>import &#39;package:responsive_builder/responsive_builder.dart&#39;;<br><br>class LoginScreen extends StatefulWidget {<br>  const LoginScreen({super.key});<br><br>  @override<br>  State&lt;LoginScreen&gt; createState() =&gt; _LoginScreenState();<br>}<br><br>class _LoginScreenState extends State&lt;LoginScreen&gt; with ObserverMixin {<br>  @override<br>  FutureOr&lt;void&gt; registerObservers() {<br>    viewModel.result.observe(this, (LoginResponse value) {<br>      if (value != null) {<br>        // login success<br>        // TODO: navigate to your destination route<br>      }<br>    });<br>  }<br><br>  @override<br>  void initState() {<br>    doRegister(); // start observing changes<br>    GetIt.instance.initProductsScope(); // register products scope<br>    super.initState();<br>  }<br><br>  @override<br>  void dispose() {<br>    GetIt.instance.dropScope(&#39;products&#39;); // clear products scope from memory<br>    doUnregister(); // stop observing changes<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final viewModel = GetIt.instance&lt;LoginViewModel&gt;();<br>    return Stack(<br>      children: [<br>        // screen body<br>        Scaffold(<br>          body: SafeArea(<br>            child: ScreenTypeLayout.builder(<br>              mobile: (_) =&gt; const LoginMobileScreen(), // &lt;-- mobile screen<br><br>              // you can remove this, then mobile screen will be displayed on tablet/iPad<br>              tablet: (_) =&gt; const LoginTabletScreen(), // &lt;-- tablet screen<br>            ),<br>          ),<br>        ),<br><br>        // full-screen loader<br>        LiveDataBuilder&lt;bool&gt;(<br>          data: viewModel.loading,<br>          builder: (BuildContext context, bool value) {<br>            if (value == true) {<br>              // display loader while request in progress<br>              return Scaffold(<br>                backgroundColor: Colors.black.withOpacity(0.05),<br>                body: const Center(child: CircularProgressIndicator.adaptive()),<br>              );<br>            }<br><br>            return const SizedBox();<br>          }<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><pre>// login_mobile_screen.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;../widgets/login_form.dart&#39;;<br><br>class LoginMobileScreen extends StatelessWidget {<br>  const LoginMobileScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return LayoutBuilder(<br>      builder: (BuildContext context, BoxConstraints constraints) =&gt; SingleChildScrollView(<br>        child: ConstrainedBox(<br>          constraints: constraints,<br><br>          // login form<br>          child: const Padding(<br>            padding: EdgeInsets.all(8.0),<br>            child: LoginForm(),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><pre>// login_tablet_screen.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;../widgets/login_form.dart&#39;;<br><br>class LoginTabletScreen extends StatelessWidget {<br>  const LoginTabletScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return LayoutBuilder(<br>      builder: (BuildContext context, BoxConstraints constraints) =&gt; SingleChildScrollView(<br>        child: ConstrainedBox(<br>          constraints: constraints,<br>          child: const Row(<br>            children: [<br>              // logo layout<br>              Placeholder(fallbackWidth: 200),<br>    <br>              // login form<br>              Expanded(<br>                child: Padding(<br>                  padding: EdgeInsets.all(8.0),<br>                  child: LoginForm(),<br>                ),<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><pre>// login_form.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;../viewmodels/login_viewmodel.dart&#39;;<br>import &#39;package:reactive_forms/reactive_forms.dart&#39;;<br><br>class LoginForm extends StatelessWidget {<br>  const LoginForm({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final viewModel = GetIt.instance&lt;LoginViewModel&gt;();<br>    final formGroup = viewModel.loginForm;<br>    return ReactiveForm(<br>      formGroup: formGroup,<br>      child: Column(<br>        children: &lt;Widget&gt;[<br>          ReactiveTextField(<br>            formControlName: &#39;email&#39;,<br>            keyboardType: TextInputType.emailAddress,<br>          ),<br>          ReactiveTextField(<br>            formControlName: &#39;password&#39;,<br>            obscureText: true,<br>          ),<br>          <br>          // Submit Button Section<br>          Padding(<br>            padding: const EdgeInsets.only(bottom: 20.0),<br>            child: SizedBox(<br>              width: double.infinity,<br>              height: 50,<br>              child: ElevatedButton(<br>                onPressed: () {<br>                  // Handle login action<br>                  viewModel.submit();<br>                },<br>                child: Text(&#39;Login&#39;),<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h4>This has the following benefits:</h4><ol><li><strong>Reduced Memory Usage</strong>: By sharing the same viewModel instance and its dependencies across multiple widgets, you avoid creating multiple instances, which helps save memory.<br>Once the user has completed the authentication flow and navigated to the home screen, you can clean up the authentication-related dependencies, ensuring that they no longer consume memory unnecessarily.</li><li><strong>Consistent State</strong>: Using a scoped singleton allows different parts of the app (like the login ProgressBar and login form widget) to access the same state and data, ensuring consistency.</li></ol><h3>What is next?</h3><p><a href="https://medium.com/@aghiadodeh/flutter-pagination-with-cache-data-objectbox-database-5d5937746828">Flutter Pagination with cache data (Objectbox Database)</a></p><h3>Full Example:</h3><p><a href="https://github.com/aghiadodeh/xflutter_cli/tree/v2.5.0/xflutter_cli_modules_application/lib/modules/authentication/presentation/screens/login">xflutter_cli/xflutter_cli_modules_application/lib/modules/authentication/presentation/screens/login at v2.5.0 · aghiadodeh/xflutter_cli</a></p><h3>UI Layer explaining:</h3><p><a href="https://xflutter-cli.com/architecture/ui-layer/intro">XFlutter CLI</a></p><h3>Dependency Injection and Scoped Singleton:</h3><p><a href="https://xflutter-cli.com/architecture/dependency-injection">XFlutter CLI</a></p><h3>Improve Productivity:</h3><p><a href="https://xflutter-cli.com/cli/intro">CLI Introduction | XFlutter CLI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f016d51515ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter CLI]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-cli-82aac708e8b3?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/82aac708e8b3</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 20:18:03 GMT</pubDate>
            <atom:updated>2024-11-20T13:31:19.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*JZRc8dDPfVCOAsuMAOrtpg.png" /></figure><p>Architects often find themselves grappling with the challenges of maintaining consistency, reducing development time, and fostering collaboration within their teams. The demand for a solution that streamlines the development process while ensuring adherence to best practices has never been greater</p><p>and the <strong>command-line interface</strong> is more than a code generator, it’s a strategic enabler that significantly reduces development time by providing pre-built, customizable components based on schematics, it unifies development teams by establishing a shared foundation. This ensures that all team members work cohesively, adopting the same conventions and best practices. New team members no longer face the daunting task of learning disparate approaches, reducing onboarding time and promoting a collaborative environment.</p><p>One of Flutter CLI tools is <a href="https://xflutter-cli.com/"><strong>x-flutter-cli</strong></a>, it helps you to generates and modifies your Flutter components based on schematic including:</p><ul><li>Create mono-repo flutter workspace (multiple apps sharing same packages).</li><li>Create modular flutter app (single app with multiple packages).</li><li>Generate screens with responsive layouts, state management, routing and theming.</li><li>Generate forms.</li><li>Generate serializable models (from json file to Freezed model).</li><li>Generate Data Layer (Http with CRUDs and caching data in local-database).</li></ul><p>Full Example for xflutter_cli:</p><p><a href="https://github.com/aghiadodeh/xflutter_cli">GitHub - aghiadodeh/xflutter_cli: CLI tool helps you to generates and/or modifies your Flutter components.</a></p><p>Official xflutter_cli docs:</p><p><a href="https://xflutter-cli.com/">XFlutter CLI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82aac708e8b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Pagination With Caching data (SQLite database) — Part 2]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-pagination-with-caching-data-sqlite-database-part-2-afb4a13a48b7?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/afb4a13a48b7</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 21:36:28 GMT</pubDate>
            <atom:updated>2024-11-28T08:36:09.830Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Pagination With Caching data (SQLite database) — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*-kEyGpImmUqFuugTyO7vTg.png" /></figure><h3>Note:</h3><h4>This Article is too old, you can check this article:</h4><p><a href="https://medium.com/@aghiadodeh/flutter-pagination-with-cache-data-objectbox-database-5d5937746828">Flutter Pagination with cache data (Objectbox Database)</a></p><h3>Configuration network environment and UI.</h3><p>In this article we’re going to build a Flutter App contains a list of “Prodcuts” and save this list in our local Storage<strong> (SQLite database), </strong>the list will be loaded and displayed small chunks of items as the user scrolls down the screen.</p><p>In Past article we talked about Configuration SQLite environment:</p><p><a href="https://medium.com/@aghiadodeh/flutter-pagination-with-caching-data-sqlite-database-part-1-ef4a22007f9e">Flutter Pagination With Caching data (SQLite database) — Part 1</a></p><p>in this article we’re going to setup our network environment and UI.</p><h3>Setup http environment:</h3><ul><li>Create Env file which contains the back-end URLs:</li><li>Create <strong>Repository</strong> the layer which send http request and get result from backend server, and fetch data from SQLite.</li></ul><p>in our <strong>Repository </strong>we’re going to create a <strong>method</strong> getProductsList() which emit to UI The request Status “Loading, Success, Error”, and <strong>Stream</strong> which emit the new status to UI</p><p>first of all don’t forget to register you database instance as a singleton:</p><pre>void main() async {</pre><pre>  WidgetsFlutterBinding.ensureInitialized();</pre><pre>GetIt.I.registerSingleton&lt;AppDatabase&gt;(await $FloorAppDatabase.databaseBuilder(‘local_app.db’).build());</pre><pre>  runApp(const MyApp());</pre><pre>}</pre><h3>Handling Status</h3><h4><strong>Loading</strong> Status:</h4><p>This status emitted by <strong>Stream</strong> when repository is fetching data (in progress…)</p><p>loading “progressBar” showing in two cases:</p><p>1- when the list is empty (fetch first page data) the progressBar will appear in the middle of screen.</p><p>2- when the list is not empty the “progressBar” will appear in the bottom of List-View.</p><h4><strong>Error </strong>Status:</h4><p>This status emitted by <strong>Stream </strong>when an exception is throwed</p><p>a Custom Widget (for example: <strong>Text</strong> Widget contains an error message) in the bottom of List-View.</p><h4><strong>Success Status:</strong></h4><p>This status emitted by <strong>Stream </strong>twice in every time you call the method getProductsList():</p><p>1- Data Fetched from SQLite.</p><p>2- Data Fetched from Back-end Response.</p><h3><strong>Handling Stream Changes</strong></h3><p>The Repository Stream is subscribed by <strong>Pagination</strong> <strong>View-Model</strong> which The Bridge between the <strong>UI </strong>layer and <strong>Repository</strong>, The View-Model listen for <strong>stream updates</strong> and update the UI when new data come from this stream.</p><p>For Pagination Logic we’re going to use pagination library <a href="https://pub.dev/packages/animated_infinite_scroll_pagination">animated_infinite_scroll_pagination</a>.</p><p>Pagination <strong>View-Model </strong>using <strong>Live Data</strong> to update the UI when Repository emit new data, for more details about <strong>Live Data</strong>:</p><p><a href="https://medium.com/@aghiadodeh/flutter-live-data-tutorial-4c65f1b7ff5e">Flutter Live Data Tutorial</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6471acec7f2536ccb918c8bcdca81a2c/href">https://medium.com/media/6471acec7f2536ccb918c8bcdca81a2c/href</a></iframe><h3>UI and View-Model</h3><p>remember that we’re using <a href="https://pub.dev/packages/animated_infinite_scroll_pagination">animated_infinite_scroll_pagination</a> to create our UI List-View</p><p>Pagination List View expected a parameter called viewmodel , this class extends PaginationViewModel.</p><p>and we’re going to create this class together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76c8f8e61aff4c776aff47a27bf5ec3d/href">https://medium.com/media/76c8f8e61aff4c776aff47a27bf5ec3d/href</a></iframe><p>Now our UI is ready to built:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40fc0dd1b3c19905a4ffe95c47f2fe41/href">https://medium.com/media/40fc0dd1b3c19905a4ffe95c47f2fe41/href</a></iframe><h3>Hope you enjoyed the tutorial.</h3><h3>The source code on GitLab:</h3><p><a href="https://gitlab.com/aghiadodeh/flutter_paging_data_with_caching">aghiad odeh / flutter_paging_data_with_caching</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afb4a13a48b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Pagination With Caching data (SQLite database) — Part 1]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-pagination-with-caching-data-sqlite-database-part-1-ef4a22007f9e?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef4a22007f9e</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 20:53:32 GMT</pubDate>
            <atom:updated>2024-11-28T08:35:28.692Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Pagination With Caching data (SQLite database) — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*-kEyGpImmUqFuugTyO7vTg.png" /></figure><h3>Note:</h3><h4>This Article is too old, you can check this article:</h4><p><a href="https://medium.com/@aghiadodeh/flutter-pagination-with-cache-data-objectbox-database-5d5937746828">Flutter Pagination with cache data (Objectbox Database)</a></p><h3>Configuration Models and SQLite (floor) environment.</h3><p>In this article we’re going to build a Flutter App contains a list of “Products” and save this list in our local Storage<strong> (SQLite database), </strong>the list will be loaded and displayed small chunks of items as the user scrolls down the screen.</p><p>In this article we’re going to use these dependencies:</p><p>1- <a href="https://pub.dev/packages/animated_infinite_scroll_pagination">animated_infinite_scroll_pagination</a>: load and display small chunks of items as the user scrolls down the screen</p><p>2- <a href="https://pub.dev/packages/floor">floor</a>: Floor provides a neat SQLite abstraction for your Flutter applications inspired by the <a href="https://developer.android.com/topic/libraries/architecture/room">Room persistence library</a>.</p><p>3- <a href="https://pub.dev/packages/dio">dio</a>: Flutter Http library</p><p>4- <a href="https://pub.dev/packages/get_it">get_it</a>: Create a singleton instance.</p><p>here we’re going to add some dependencies to our new flutter project. Our pubspec.yaml should look something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7bb3ce4fe9b64b020022b267e67d923/href">https://medium.com/media/e7bb3ce4fe9b64b020022b267e67d923/href</a></iframe><p>Our Project at the end of this article will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*iht8bMeCgMFnPx9gTDZFag.png" /></figure><h3>1- Setup Product Models:</h3><p>Our Server return a list of data “<strong>Product</strong>” in Response like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eec77a49c096fe0f2c6477f541e272e/href">https://medium.com/media/7eec77a49c096fe0f2c6477f541e272e/href</a></iframe><p>So we’re going to create our models like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25c25eb5469e6b8eabbba697867f4314/href">https://medium.com/media/25c25eb5469e6b8eabbba697867f4314/href</a></iframe><p>You will show errors in “base_response.dart” and “list_response.dart”</p><p>to fix them generate this command in your terminal</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><h3>2- Setup SQLite environment:</h3><p>for SQLite we’re going to use <a href="https://pub.dev/packages/floor">floor</a> library, for more info visit: <a href="https://floor.codes/getting-started/">https://floor.codes/getting-started/</a></p><p>SQLite <strong>Architecture </strong>contains:</p><ul><li>Entity: An entity is a persistent class. Floor automatically creates the mappings between the in-memory objects and database table rows.</li><li>Dao (Data Access Object): When you use the SQLite library to store your app’s data, you interact with the stored data by defining <strong>data access objects, </strong>Each DAO includes methods that offer abstract access to your app’s database.</li><li>Converters: SQLite allows storing values of only a handful types. Whenever more complex Dart in-memory objects should be stored, there sometimes is the need for converting between Dart and SQLite compatible types.</li><li>Database: abstract class contains all DAOs, database version, entities and converters.</li></ul><h4>Create Entity:</h4><p>It will represent a database table as well as the scaffold of your business object. @entity marks the class as a persistent class. It&#39;s required to add a primary key to your table. You can do so by adding the @primaryKey</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2d89903389a5ffa32567bed64519ab/href">https://medium.com/media/eb2d89903389a5ffa32567bed64519ab/href</a></iframe><h4>Create Dao (Data Access Object):</h4><p>This component is responsible for managing access to the underlying SQLite database. The abstract class contains the method signatures for querying the database which have to return a Future or Stream.</p><ul><li>You can define queries by adding the @Query annotation to a method. The SQL statement has to get added in parenthesis. The method must return a Future or Stream of the Entity you&#39;re querying for.</li><li>@insert marks a method as an insertion method.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eaa1714dc06e4de5934507e348baf40/href">https://medium.com/media/6eaa1714dc06e4de5934507e348baf40/href</a></iframe><h4>Create Converter:</h4><p>Convert Product Images model to String to be able to save it in SQLite:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c667e9791c5e5adf73c0e51568b1c8e/href">https://medium.com/media/2c667e9791c5e5adf73c0e51568b1c8e/href</a></iframe><h4>Create Database:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56dacbd2b812a977e1a5499c56de9a67/href">https://medium.com/media/56dacbd2b812a977e1a5499c56de9a67/href</a></iframe><p>to generate database.g.dart run this command in your terminal:</p><pre>flutter pub run build_runner build — delete-conflicting-outputs</pre><p>Part 2:</p><p><a href="https://medium.com/@aghiadodeh/flutter-pagination-with-caching-data-sqlite-database-part-2-afb4a13a48b7">Flutter Pagination With Caching data (SQLite database) — Part 2</a></p><h3>The source code on GitLab:</h3><p><a href="https://gitlab.com/aghiadodeh/flutter_paging_data_with_caching">aghiad odeh / flutter_paging_data_with_caching</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef4a22007f9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Live Data Tutorial]]></title>
            <link>https://medium.com/@aghiadodeh/flutter-live-data-tutorial-4c65f1b7ff5e?source=rss-321766499566------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c65f1b7ff5e</guid>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Aghiad Odeh]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 17:48:38 GMT</pubDate>
            <atom:updated>2023-08-05T07:12:48.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*54xyWq1vDFnVjL7zJC71fQ.png" /></figure><p>In this article we’re going to learn about “LiveData” which is <strong>an observable data holder class.</strong></p><p>we’re going to use flutter live data library: <a href="https://pub.dev/packages/flutterx_live_data">flutterx_live_data</a></p><p>Live Data is a wrapper on an object which can be observed from any UI component, and it is a core architecture component in android native (Java and Kotlin), and we will use the same concept in flutter.</p><h3>Handle Data changed in UI with a few lines of code.</h3><p>To better understand when to use this new observable data holder and the advantages of using it, in the rest of this post I’ll review some of the alternatives to face the fundamental task of updating the UI based on data changes:</p><ul><li>Managing data in the UI component.</li><li>Synchronous Update between <strong>View </strong>and<strong> View-Model.</strong></li><li>Transformations &amp; Combine LiveData.</li></ul><p>If you consider using many variables and you want to listen to this variables changes, the first thing that comes to mind to use Provider or Cubit.</p><p>We’re find a simple way, and this way is using Live Data</p><p>Before talking about Managing data in the UI component, let’s create a simple class contains multi variables and call this Class “LiveDataViewModel”</p><h3>Initialize Live Data:</h3><p>import flutter live data library:</p><pre>import ‘package:flutterx_live_data/flutterx_live_data.dart’;</pre><p>declare a variable Integer “counter1” with initial value “0”.</p><pre>class LiveDataViewModel {</pre><pre>MutableLiveData&lt;int&gt; counter1 = MutableLiveData&lt;int&gt;(value: 0);</pre><pre>}</pre><p>“MutableLiveData&lt;T&gt;” means you have a <strong>LiveData </strong>object with mutable values and the initial value is required, “T” is the type of variable wrapped in the <strong>LiveData </strong>object (int, bool, String, double …).</p><p>You can access the <strong>LiveData</strong> latest value by “someVariable.value”.</p><h3>Update Live Data:</h3><p>let’s declare a function and call it “increment1”, and this function increase “counter1” value by “1”.</p><p>Update Live Data Value:</p><pre>increment1() {</pre><pre>   counter1.postValue(counter1.value + 1);</pre><pre>}</pre><p>The Difference of <strong>setValue </strong>&amp; <strong>postValue </strong>in MutableLiveData is:</p><h4><strong>setValue:</strong></h4><p>Sets the value. If there are active observers, the value will be dispatched to them. This method must be called from the main thread.</p><h4><strong>postValue:</strong></h4><p>Posts a task to a main thread to set the given value. If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.</p><h3>Observe Live Data in UI:</h3><p>You can use a LiveDataBuilder&lt;TypeOfVariable&gt; Widget which is provided by <a href="https://pub.dev/packages/flutterx_live_data">flutterx_live_data</a> library.</p><p>This widget expected 2 parameters:</p><p>1- <strong><em>builder</em></strong>: in this builder you going to wrap your widget, Builder return the last <strong>Live Data value</strong></p><pre>builder: (context, value) { <br>      // value is the last live-data variable value <br>      return YourWidget;<br>}</pre><p>2- <strong><em>data</em></strong>: The Live Data variable you want to listen when value changed, and when this variable value changed, the builder will rebuilt.</p><p>We’re going to observe our “counter1” like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eb208fcbca5ec2cebce9df76172674e/href">https://medium.com/media/7eb208fcbca5ec2cebce9df76172674e/href</a></iframe><h3>Observe Live Data in non-Context Class:</h3><p>You can use a ObserverWrapper&lt;TypeOfVariable&gt; Widget which is provided by <a href="https://pub.dev/packages/flutterx_live_data">flutterx_live_data</a> library.</p><h4>Usage:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cebae0931424ceb0abac37f7c5279ce8/href">https://medium.com/media/cebae0931424ceb0abac37f7c5279ce8/href</a></iframe><p>the result in your debug console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*Ql8MI_uLNby8wCSgy7fpyQ.png" /></figure><h3>Combine Live Data in UI:</h3><p>if we have a second variable called “counter2” and this variable increased by “value + 2” from function “increment2()”</p><pre>MutableLiveData&lt;int&gt; counter2 = MutableLiveData(value: 0);</pre><pre>/// increment counter2 value</pre><pre>increment2() {</pre><pre>   counter2.postValue(counter2.value + 2);</pre><pre>}</pre><p>and we want to listen for “counter1” and “counter2” changes in same widget</p><p>Flutter Live Data give us the solution to resolve this issue by using:</p><pre>CombinedLiveDataBuilder.with2&lt;Type1, Type2, transformType&gt;</pre><p><strong>Combine Live Data Builder </strong>is Built to observe for multi Live Data variables (min is <strong>2</strong>, max is <strong>4</strong>), the transform Computes value from [data] sources and pass this value to “<strong>Combine Live Data Builder” </strong>builder.</p><p>But what if we have more than 4 LiveData variables and we want to observe for all of them?</p><p>we can use MediatorLiveData&lt;T&gt;</p><p>MediatorLiveData is a subclass of MutableLiveData made for the situation where you want to observe changes parallel from Multiple LiveData instances.</p><pre>MediatorMutableLiveData&lt;bool&gt; isValid = MediatorMutableLiveData(value: false);</pre><p>Observe for multiple live data changes: (for example we will add only 2 liveData variables and you can add unlimited liveData variables)</p><pre>isValid.addSource(email, (value) =&gt; validateForm());</pre><pre>isValid.addSource(password, (value) =&gt; validateForm());</pre><p>in our example above we tell “isValid” variable that when “email” or “password” value changed call the method “validateForm” and this method will change the “isValid” value depending on “email” and “password” value.</p><pre>void validateForm() {</pre><pre> bool valid = email.value.isNotEmpty &amp;&amp; password.value.isNotEmpty;</pre><pre> isValid.postValue(valid);</pre><pre>}</pre><p>our example be like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/596a1256ce4078374c92a09a1c039e9f/href">https://medium.com/media/596a1256ce4078374c92a09a1c039e9f/href</a></iframe><p>The Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_3ATiMXcp04WjYb4vJlO3A.gif" /></figure><p>The full example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae5b75c0f9d64cc0bb25cb6abfebb54/href">https://medium.com/media/bae5b75c0f9d64cc0bb25cb6abfebb54/href</a></iframe><h3>Hope you enjoyed the tutorial.</h3><h3>Where to Go From Here?</h3><p>you can see our Login Tutorial example using Live Data:</p><p><a href="https://medium.com/@aghiadodeh/flutter-login-tutorial-with-validation-live-data-freezed-models-secure-local-storage-part-1-52d7632fc8e3">Flutter Login Tutorial with (Validation, Live Data, @Freezed Models, Secure Local Storage) — Part 1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c65f1b7ff5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>