<?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 Asifulhaque on Medium]]></title>
        <description><![CDATA[Stories by Asifulhaque on Medium]]></description>
        <link>https://medium.com/@asifulhaque1144?source=rss-1213a3158335------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iVuiBY6_iCD8u0Fz</url>
            <title>Stories by Asifulhaque on Medium</title>
            <link>https://medium.com/@asifulhaque1144?source=rss-1213a3158335------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:17:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asifulhaque1144/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[ A Complete Beginner-to-Advanced Guide to Git (Part-I)]]></title>
            <link>https://medium.com/@asifulhaque1144/a-complete-beginner-to-advanced-guide-to-git-part-i-6e18dc922e41?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e18dc922e41</guid>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 18:29:17 GMT</pubDate>
            <atom:updated>2026-02-11T18:29:17.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFRgkuZR3GZLS_fdNaa4ug.png" /></figure><p>Git is one of the most powerful and widely used version control systems in software development. Whether you are a beginner or an intermediate developer, understanding Git is essential for efficient collaboration and managing code history.</p><p>In this guide, we will walk through everything — from installation to advanced features like cherry-pick, rebase, merge conflicts, and more.</p><h3>1. Installing Git on Windows, Linux/Ubuntu, and macOS</h3><h3>Windows</h3><ol><li>Visit the official download page: <a href="https://git-scm.com/downloads">https://git-scm.com/downloads</a></li><li>Download <strong>“Git for Windows”</strong>.</li><li>Run the installer → keep default options.</li><li>Open Git Bash to verify installation:</li></ol><pre>git --version</pre><h3>Linux / Ubuntu</h3><p>Open Terminal and run:</p><pre>sudo apt update<br>sudo apt install git<br>git --version</pre><h3>macOS</h3><p>Using Homebrew:</p><pre>brew install git</pre><p>Or install Xcode Command Line Tools:</p><pre>xcode-select --install<br>git --version</pre><h3>2. Setting Global Git Username and Email</h3><p>Configure your name and email (used in all commits):</p><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;your.email@example.com&quot;</pre><p>Check configuration:</p><pre>git config --global --list</pre><h3>3. Setting Up Git SSH Key</h3><p>Generate SSH key:</p><pre>ssh-keygen -t ed25519 -C &quot;your.email@example.com&quot;</pre><p>Start SSH agent:</p><pre>eval &quot;$(ssh-agent -s)&quot;<br>ssh-add ~/.ssh/id_ed25519</pre><p>Copy your public key:</p><pre>cat ~/.ssh/id_ed25519.pub</pre><p>Add the key to GitHub/GitLab → Settings → SSH Keys.</p><p>Test connection:</p><pre>ssh -T git@github.com</pre><h3>4. Setting Remote, Checking Remote, Adding &amp; Removing Remote</h3><p>Check current remote:</p><pre>git remote -v</pre><p>Add remote:</p><pre>git remote add origin git@github.com:username/repo.git</pre><p>Change remote:</p><pre>git remote set-url origin new-url</pre><p>Remove remote:</p><pre>git remote remove origin</pre><h3><strong>5. How to Clone a Repository</strong></h3><pre>git clone https://github.com/user/repo.git</pre><p>With SSH:</p><pre>git clone git@github.com:user/repo.git</pre><h3><strong>6. How to Create a Branch</strong></h3><p>Create branch:</p><pre>git branch feature/login</pre><p>Switch branch:</p><pre>git checkout feature/login</pre><p>OR create + switch:</p><pre>git checkout -b feature/login</pre><h3><strong>7. How to Fetch Git Changes</strong></h3><p>Fetch (only download changes):</p><pre>git fetch</pre><p>Fetch + merge:</p><pre>git pull</pre><p>Fetch specific branch:</p><pre>git fetch origin main</pre><h3><strong>8. How to Commit Changes</strong></h3><p>Stage files:</p><pre>git add .</pre><p>Commit:</p><pre>git commit -m &quot;Your commit message&quot;</pre><p>Commit specific file:</p><pre>git add file.txt<br>git commit -m &quot;Updated file&quot;</pre><h3>9. What is Git Stash? How to Use It</h3><p>Stash lets you save uncommitted work temporarily.</p><p>Save work:</p><pre>git stash</pre><p>Apply latest stash:</p><pre>git stash apply</pre><p>List stashes:</p><pre>git stash list</pre><p>Drop stash:</p><pre>git stash drop</pre><h3>10. What Is Amend Commit?</h3><p>Amend allows you to modify your last commit.</p><p>Modify the commit message:</p><pre>git commit --amend -m &quot;New message&quot;</pre><p>Add forgotten files:</p><pre>git add missing-file.txt<br>git commit --amend</pre><p>⚠️ Avoid using amend after pushing the commit.</p><h3>11. How to View Commit Logs</h3><p>Simple log:</p><pre>git log</pre><p>One-line view:</p><pre>git log --oneline</pre><p>Graph view:</p><pre>git log --oneline --graph --decorate --all</pre><h3>12. How to Use Cherry-pick</h3><p>Cherry-pick copies a specific commit to your current branch.</p><pre>git cherry-pick &lt;commit-hash&gt;</pre><p>To avoid merge conflicts, always cherry-pick onto updated branches.</p><h3>13. How to Push and Push Forcefully</h3><p>Push normally:</p><pre>git push origin main</pre><p>Push a branch:</p><pre>git push -u origin feature/login</pre><p>Force push:</p><pre>git push --force</pre><p>Use force-with-lease (safer):</p><pre>git push --force-with-lease</pre><h3>14. Difference Between Rebase and Merge</h3><h4>Merge</h4><ul><li>Combines branches.</li><li>Creates a merge commit.</li><li>Keeps commit history as-is.</li></ul><pre>git merge feature/login</pre><h4>Rebase</h4><ul><li>Moves your branch on top of another branch.</li><li>Creates a cleaner, linear history.</li><li>Rewrites commit history.</li></ul><pre>git rebase main</pre><p><strong>Simple Comparison</strong></p><pre>| Merge              | Rebase                 |<br>| ------------------ | ---------------------- |<br>| Keeps history      | Rewrites history       |<br>| Safe after pushing | Not safe after pushing |<br>| Has merge commits  | Clean commit history   |</pre><h3>15. How to Resolve Merge Conflicts</h3><p>When Git shows conflict:</p><ol><li>Open affected file:</li></ol><pre>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD<br>Your changes<br>=======<br>Incoming changes<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt; branch-to-merge</pre><p>2. Manually edit and keep required lines.</p><p>3. Mark as resolved:</p><pre>git add .</pre><p>4. Continue merge:</p><pre>git commit</pre><h3>16. What is .gitignore</h3><p>The .gitignore file tells Git which files/folders to ignore.</p><p>Examples:</p><pre>/build<br>/node_modules<br>*.log<br>.env</pre><h3>17. What if You Forgot to Add .gitignore Initially?</h3><ol><li>Add your .gitignore file.</li><li>Remove already-tracked unwanted files:</li></ol><pre>git rm -r --cached .<br>git add .<br>git commit -m &quot;Updated .gitignore&quot;</pre><p>This removes files from Git but keeps them locally.</p><h3>18. What Is Git Hard Reset?</h3><p>Hard reset wipes out local changes <strong>completely</strong>.</p><pre>git reset --hard HEAD</pre><p>Reset to previous commit:</p><pre>git reset --hard &lt;commit-hash&gt;</pre><p>⚠️ Dangerous — cannot recover easily.</p><h3>19. How to Send a Merge Request (Pull Request)</h3><h4>GitHub</h4><ol><li>Push your branch.</li><li>Go to GitHub → Your repo.</li><li>Click <strong>New Pull Request</strong>.</li><li>Select source branch → target branch.</li><li>Add title &amp; description.</li><li>Create Pull Request.</li></ol><h4>GitLab</h4><p>Similar:<br> <strong>Merge Requests → New → Select branches → Submit.</strong></p><h3>20. How to Merge Into Main Branch</h3><p>From GitHub/GitLab UI:</p><ul><li>Review → Approve → Merge.</li></ul><p>Or merge manually with Git:</p><pre>git checkout main<br>git pull<br>git merge feature/login<br>git push origin main</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e18dc922e41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Part 3 — Presentation Layer (Cubit + UI) | Flutter Clean Architecture + BLoC + Isar]]></title>
            <link>https://medium.com/@asifulhaque1144/part-3-presentation-layer-cubit-ui-flutter-clean-architecture-bloc-isar-bd29ed505c05?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd29ed505c05</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[bloc-architecture]]></category>
            <category><![CDATA[isar]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 17:18:10 GMT</pubDate>
            <atom:updated>2025-11-18T17:18:10.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>📘 Part 3 — Presentation Layer (Cubit + UI) | Flutter Clean Architecture + BLoC + Isar</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUkwY4lrsw1iylzve0zlag.png" /></figure><p>Welcome to the <strong>final part</strong> of our 3-part of Flutter Clean Architecture series!</p><p>In <a href="https://medium.com/@asifulhaque1144/flutter-clean-architecture-with-bloc-isar-part-1-c59364dea046"><strong>Part 1</strong></a>, we have discussed about the <strong><em>Project Structure</em></strong>.<br> In <a href="https://medium.com/@asifulhaque1144/flutter-clean-architecture-with-bloc-isar-part-2-26fd38215f1e"><strong>Part 2</strong></a>, we built the <strong><em>Domain and Data Layer</em></strong> with Isar local caching and Dio networking.</p><p>Now, in <strong>Part 3</strong>, we focus on the <strong>Presentation Layer</strong> — where everything comes alive.</p><p>This is where:</p><ul><li>Our Cubit interacts with the use cases</li><li>Our UI listens to state changes</li><li>Pagination, refresh logic, and search come together</li><li>The user finally <em>sees</em> the GitHub repositories</li></ul><p>Let’s dive in.</p><h3>🎯 What We Will Build in Part 3</h3><p>Our presentation layer consists of:</p><h4>✔️ Cubit Layer</h4><ul><li>repository_cubit.dart – Holds presentation logic &amp; interacts with use cases</li><li>repository_state.dart – All possible UI states</li></ul><h4>✔️ UI Layer</h4><ul><li>home_page.dart – Full UI with search, infinite scroll, and pull-to-refresh</li></ul><h4>✔️ Widgets</h4><ul><li>repository_list_item.dart – A reusable component for displaying each repository</li></ul><h4>✔️ App Entry Point</h4><ul><li>Updated main.dart to attach DI &amp; routing</li></ul><h3>🧠 Why These Files Are Required</h3><h3>1️⃣ Cubit + State (Presentation Logic Layer)</h3><p>The <strong>cubit</strong> takes care of:</p><ul><li>Loading repositories</li><li>Loading more pages (infinite scroll)</li><li>Refreshing</li><li>Searching</li><li>Error handling</li></ul><p>The <strong>state classes</strong> define:</p><ul><li>Loading</li><li>Loaded</li><li>Error</li><li>Refreshing</li><li>Pagination state</li></ul><p>This separation keeps UI clean and reactive.</p><h4>📂 presentation/cubit/repository_state.dart</h4><pre>abstract class RepositoryState extends Equatable {<br>  const RepositoryState();<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [];<br>}<br><br>class RepositoryInitial extends RepositoryState {}<br><br>class RepositoryLoading extends RepositoryState {}<br><br>class RepositoryLoaded extends RepositoryState {<br>  final List&lt;RepositoryEntity&gt; repositories;<br>  final bool hasReachedEnd;<br>  final int currentPage;<br>  final int totalItems;<br>  final String query;<br><br>  const RepositoryLoaded({<br>    required this.repositories,<br>    required this.hasReachedEnd,<br>    required this.currentPage,<br>    required this.totalItems,<br>    required this.query,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [repositories, hasReachedEnd, currentPage, totalItems, query];<br><br>  RepositoryLoaded copyWith({<br>    List&lt;RepositoryEntity&gt;? repositories,<br>    bool? hasReachedEnd,<br>    int? currentPage,<br>    int? totalItems,<br>    String? query,<br>  }) {<br>    return RepositoryLoaded(<br>      repositories: repositories ?? this.repositories,<br>      hasReachedEnd: hasReachedEnd ?? this.hasReachedEnd,<br>      currentPage: currentPage ?? this.currentPage,<br>      totalItems: totalItems ?? this.totalItems,<br>      query: query ?? this.query,<br>    );<br>  }<br>}<br><br>class RepositoryError extends RepositoryState {<br>  final String message;<br><br>  const RepositoryError(this.message);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [message];<br>}<br><br>class RepositoryRefreshing extends RepositoryState {<br>  final List&lt;RepositoryEntity&gt; currentRepositories;<br><br>  const RepositoryRefreshing(this.currentRepositories);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [currentRepositories];<br>}<br><br>class RepositoryLoadingMore extends RepositoryState {<br>  final List&lt;RepositoryEntity&gt; currentRepositories;<br>  final int currentPage;<br>  final String query;<br><br>  const RepositoryLoadingMore({<br>    required this.currentRepositories,<br>    required this.currentPage,<br>    required this.query,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [currentRepositories, currentPage, query];<br>}</pre><h4>📂 presentation/cubit/repository_cubit.dart</h4><p>The cubit orchestrates the flow between UI and domain use cases:</p><ul><li>loadRepositories() → initial load</li><li>loadMoreRepositories() → pagination</li><li>refreshAllRepositories() → pull-to-refresh</li><li>searchRepositories() → search</li></ul><pre>class RepositoryCubit extends Cubit&lt;RepositoryState&gt; {<br>  final GetRepositories getRepositories;<br>  final RefreshRepositories refreshRepositories;<br>  final GetTotalCount getTotalCount;<br><br>  RepositoryCubit({<br>    required this.getRepositories,<br>    required this.refreshRepositories,<br>    required this.getTotalCount,<br>  }) : super(RepositoryInitial());<br><br>  Future&lt;void&gt; loadRepositories({<br>    String query = &#39;flutter&#39;,<br>    int perPage = ApiConstants.defaultPerPage,<br>  }) async {<br>    emit(RepositoryLoading());<br><br>    // Get total count first<br>    final totalCountResult = await getTotalCount(query);<br><br>    totalCountResult.fold(<br>          (failure) =&gt; emit(RepositoryError(_mapFailureToMessage(failure))),<br>          (totalCount) async {<br>        final params = RepositoryParams(<br>          page: 1,<br>          perPage: perPage,<br>          query: query,<br>        );<br><br>        final result = await getRepositories(params);<br><br>        result.fold(<br>              (failure) =&gt; emit(RepositoryError(_mapFailureToMessage(failure))),<br>              (repositories) {<br>            final hasReachedEnd = repositories.length &gt;= totalCount;<br><br>            emit(RepositoryLoaded(<br>              repositories: repositories,<br>              hasReachedEnd: hasReachedEnd,<br>              currentPage: 1,<br>              totalItems: totalCount,<br>              query: query,<br>            ));<br>          },<br>        );<br>      },<br>    );<br>  }<br><br>  Future&lt;void&gt; loadMoreRepositories({<br>    int perPage = ApiConstants.defaultPerPage,<br>  }) async {<br>    // Only proceed if in loaded state<br>    if (state is RepositoryLoaded) {<br>      final currentState = state as RepositoryLoaded;<br><br>      // Don&#39;t load more if already reached the end<br>      if (currentState.hasReachedEnd) return;<br><br>      emit(RepositoryLoadingMore(<br>        currentRepositories: currentState.repositories,<br>        currentPage: currentState.currentPage,<br>        query: currentState.query,<br>      ));<br><br>      final nextPage = currentState.currentPage + 1;<br><br>      final params = RepositoryParams(<br>        page: nextPage,<br>        perPage: perPage,<br>        query: currentState.query,<br>      );<br><br>      final result = await getRepositories(params);<br><br>      result.fold(<br>            (failure) =&gt; emit(RepositoryError(_mapFailureToMessage(failure))),<br>            (newRepositories) {<br>          final allRepositories = [<br>            ...currentState.repositories,<br>            ...newRepositories,<br>          ];<br><br>          final hasReachedEnd = allRepositories.length &gt;= currentState.totalItems;<br><br>          emit(RepositoryLoaded(<br>            repositories: allRepositories,<br>            hasReachedEnd: hasReachedEnd,<br>            currentPage: nextPage,<br>            totalItems: currentState.totalItems,<br>            query: currentState.query,<br>          ));<br>        },<br>      );<br>    }<br>  }<br><br>  Future&lt;void&gt; refreshAllRepositories({<br>    int perPage = ApiConstants.defaultPerPage,<br>  }) async {<br>    // Only proceed if in loaded state<br>    if (state is RepositoryLoaded) {<br>      final currentState = state as RepositoryLoaded;<br><br>      emit(RepositoryRefreshing(currentState.repositories));<br><br>      // Get total count first for fresh data<br>      final totalCountResult = await getTotalCount(currentState.query);<br><br>      totalCountResult.fold(<br>            (failure) =&gt; emit(RepositoryError(_mapFailureToMessage(failure))),<br>            (totalCount) async {<br>          final params = RepositoryParams(<br>            page: 1,<br>            perPage: perPage,<br>            query: currentState.query,<br>          );<br><br>          final result = await refreshRepositories(params);<br><br>          result.fold(<br>                (failure) =&gt; emit(RepositoryError(_mapFailureToMessage(failure))),<br>                (repositories) {<br>              final hasReachedEnd = repositories.length &gt;= totalCount;<br><br>              emit(RepositoryLoaded(<br>                repositories: repositories,<br>                hasReachedEnd: hasReachedEnd,<br>                currentPage: 1,<br>                totalItems: totalCount,<br>                query: currentState.query,<br>              ));<br>            },<br>          );<br>        },<br>      );<br>    } else {<br>      // If not in loaded state, just do a normal load<br>      loadRepositories(perPage: perPage);<br>    }<br>  }<br><br>  Future&lt;void&gt; searchRepositories({<br>    required String query,<br>    int perPage = ApiConstants.defaultPerPage,<br>  }) async {<br>    emit(RepositoryLoading());<br><br>    // Get total count first<br>    final totalCountResult = await getTotalCount(query);<br><br>    totalCountResult.fold(<br>          (failure) =&gt; emit(RepositoryError(_mapFailureToMessage(failure))),<br>          (totalCount) async {<br>        final params = RepositoryParams(<br>          page: 1,<br>          perPage: perPage,<br>          query: query,<br>        );<br><br>        final result = await refreshRepositories(params);<br><br>        result.fold(<br>              (failure) =&gt; emit(RepositoryError(_mapFailureToMessage(failure))),<br>              (repositories) {<br>            final hasReachedEnd = repositories.length &gt;= totalCount;<br><br>            emit(RepositoryLoaded(<br>              repositories: repositories,<br>              hasReachedEnd: hasReachedEnd,<br>              currentPage: 1,<br>              totalItems: totalCount,<br>              query: query,<br>            ));<br>          },<br>        );<br>      },<br>    );<br>  }<br><br>  String _mapFailureToMessage(Failure failure) {<br>    switch (failure.runtimeType) {<br>      case ServerFailure:<br>        return failure.message;<br>      case CacheFailure:<br>        return failure.message;<br>      case NetworkFailure:<br>        return failure.message;<br>      default:<br>        return ErrorMessages.unknownError;<br>    }<br>  }<br>}</pre><h3>🖥️ UI Layer</h3><h3>2️⃣ Home Page — where the entire UX comes together</h3><p>In this screen we handle:</p><p>✔ Search field<br> ✔ Scroll listener for infinite scroll<br> ✔ Pull-to-refresh<br> ✔ Displaying loading, refreshing &amp; paginating states<br> ✔ Showing repository list</p><h4><strong>📂 pages/home_page.dart</strong></h4><pre>class HomePage extends StatefulWidget {<br>  const HomePage({Key? key}) : super(key: key);<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  final TextEditingController _searchController = TextEditingController();<br>  final ScrollController _scrollController = ScrollController();<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _scrollController.addListener(_onScroll);<br><br>    // Load repositories when the widget is first built<br>    context.read&lt;RepositoryCubit&gt;().loadRepositories();<br>  }<br><br>  @override<br>  void dispose() {<br>    _searchController.dispose();<br>    _scrollController.removeListener(_onScroll);<br>    _scrollController.dispose();<br>    super.dispose();<br>  }<br><br>  void _onScroll() {<br>    if (_scrollController.position.pixels &gt;=<br>        _scrollController.position.maxScrollExtent - 200) {<br>      final state = context.read&lt;RepositoryCubit&gt;().state;<br>      if (state is RepositoryLoaded &amp;&amp; !state.hasReachedEnd) {<br>        context.read&lt;RepositoryCubit&gt;().loadMoreRepositories();<br>      }<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;GitHub Repositories&#39;),<br>      ),<br>      body: Column(<br>        children: [<br>          Padding(<br>            padding: const EdgeInsets.all(16),<br>            child: TextField(<br>              controller: _searchController,<br>              decoration: InputDecoration(<br>                hintText: &#39;Search repositories...&#39;,<br>                prefixIcon: const Icon(Icons.search),<br>                suffixIcon: IconButton(<br>                  icon: const Icon(Icons.clear),<br>                  onPressed: () {<br>                    _searchController.clear();<br>                    context.read&lt;RepositoryCubit&gt;().loadRepositories();<br>                  },<br>                ),<br>                border: OutlineInputBorder(<br>                  borderRadius: BorderRadius.circular(8),<br>                ),<br>              ),<br>              onSubmitted: (query) {<br>                if (query.isNotEmpty) {<br>                  context.read&lt;RepositoryCubit&gt;().searchRepositories(query: query);<br>                }<br>              },<br>            ),<br>          ),<br>          Expanded(<br>            child: BlocBuilder&lt;RepositoryCubit, RepositoryState&gt;(<br>              builder: (context, state) {<br>                if (state is RepositoryInitial) {<br>                  return const Center(child: CircularProgressIndicator());<br>                } else if (state is RepositoryLoading) {<br>                  return const Center(child: CircularProgressIndicator());<br>                } else if (state is RepositoryLoaded) {<br>                  return _buildRepositoryList(state.repositories);<br>                } else if (state is RepositoryRefreshing) {<br>                  return _buildRepositoryList(state.currentRepositories, isRefreshing: true);<br>                } else if (state is RepositoryLoadingMore) {<br>                  return _buildRepositoryList(state.currentRepositories, isLoadingMore: true);<br>                } else if (state is RepositoryError) {<br>                  return Center(<br>                    child: Column(<br>                      mainAxisAlignment: MainAxisAlignment.center,<br>                      children: [<br>                        Text(state.message),<br>                        const SizedBox(height: 16),<br>                        ElevatedButton(<br>                          onPressed: () {<br>                            context.read&lt;RepositoryCubit&gt;().loadRepositories();<br>                          },<br>                          child: const Text(&#39;Try Again&#39;),<br>                        ),<br>                      ],<br>                    ),<br>                  );<br>                } else {<br>                  return const Center(child: Text(&#39;Unknown State&#39;));<br>                }<br>              },<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br><br>  Widget _buildRepositoryList(<br>      List&lt;dynamic&gt; repositories, {<br>        bool isRefreshing = false,<br>        bool isLoadingMore = false,<br>      }) {<br>    return RefreshIndicator(<br>      onRefresh: () async {<br>        await context.read&lt;RepositoryCubit&gt;().refreshAllRepositories();<br>      },<br>      child: repositories.isEmpty<br>          ? const Center(child: Text(&#39;No repositories found&#39;))<br>          : Stack(<br>        children: [<br>          ListView.builder(<br>            controller: _scrollController,<br>            itemCount: repositories.length + (isLoadingMore ? 1 : 0),<br>            itemBuilder: (context, index) {<br>              if (index == repositories.length) {<br>                // Loading indicator at the bottom<br>                return const Center(<br>                  child: Padding(<br>                    padding: EdgeInsets.all(16.0),<br>                    child: CircularProgressIndicator(),<br>                  ),<br>                );<br>              }<br>              return RepositoryListItem(repository: repositories[index]);<br>            },<br>          ),<br>          if (isRefreshing)<br>            const Positioned(<br>              top: 0,<br>              left: 0,<br>              right: 0,<br>              child: LinearProgressIndicator(),<br>            ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h3>🧩 3️⃣ Common Widget — RepositoryListItem</h3><p>To keep UI modular, we extract each repository item into a dedicated widget.</p><p>This reduces duplication and improves readability</p><h4>📂 widgets/repository_list_item.dart</h4><pre>class RepositoryListItem extends StatelessWidget {<br>  final RepositoryEntity repository;<br><br>  const RepositoryListItem({<br>    Key? key,<br>    required this.repository,<br>  }) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Card(<br>      elevation: 2,<br>      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),<br>      child: InkWell(<br>        onTap: () {<br>          // Could navigate to detail page or launch URL<br>        },<br>        child: Padding(<br>          padding: const EdgeInsets.all(16),<br>          child: Column(<br>            crossAxisAlignment: CrossAxisAlignment.start,<br>            children: [<br>              Row(<br>                children: [<br>                  CircleAvatar(<br>                    backgroundImage: NetworkImage(repository.ownerAvatarUrl),<br>                    radius: 20,<br>                  ),<br>                  const SizedBox(width: 12),<br>                  Expanded(<br>                    child: Column(<br>                      crossAxisAlignment: CrossAxisAlignment.start,<br>                      children: [<br>                        Text(<br>                          repository.name,<br>                          style: const TextStyle(<br>                            fontWeight: FontWeight.bold,<br>                            fontSize: 16,<br>                          ),<br>                          maxLines: 1,<br>                          overflow: TextOverflow.ellipsis,<br>                        ),<br>                        const SizedBox(height: 4),<br>                        Text(<br>                          repository.ownerLogin,<br>                          style: TextStyle(<br>                            color: Colors.grey[600],<br>                            fontSize: 14,<br>                          ),<br>                        ),<br>                      ],<br>                    ),<br>                  ),<br>                ],<br>              ),<br>              if (repository.description.isNotEmpty) ...[<br>                const SizedBox(height: 12),<br>                Text(<br>                  repository.description,<br>                  style: const TextStyle(fontSize: 14),<br>                  maxLines: 3,<br>                  overflow: TextOverflow.ellipsis,<br>                ),<br>              ],<br>              const SizedBox(height: 12),<br>              Row(<br>                children: [<br>                  _buildStat(Icons.star_border, repository.stargazersCount.toString()),<br>                  const SizedBox(width: 16),<br>                  _buildStat(Icons.call_split, repository.forksCount.toString()),<br>                  const SizedBox(width: 16),<br>                  _buildStat(Icons.remove_red_eye_outlined, repository.watchersCount.toString()),<br>                  const Spacer(),<br>                  if (repository.language.isNotEmpty &amp;&amp; repository.language != &#39;Unknown&#39;)<br>                    _buildLanguageChip(repository.language),<br>                ],<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  Widget _buildStat(IconData icon, String count) {<br>    return Row(<br>      children: [<br>        Icon(icon, size: 16, color: Colors.grey[600]),<br>        const SizedBox(width: 4),<br>        Text(count, style: TextStyle(color: Colors.grey[600])),<br>      ],<br>    );<br>  }<br><br>  Widget _buildLanguageChip(String language) {<br>    return Container(<br>      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),<br>      decoration: BoxDecoration(<br>        color: _getLanguageColor(language).withOpacity(0.1),<br>        borderRadius: BorderRadius.circular(12),<br>        border: Border.all(color: _getLanguageColor(language)),<br>      ),<br>      child: Text(<br>        language,<br>        style: TextStyle(<br>          color: _getLanguageColor(language),<br>          fontSize: 12,<br>        ),<br>      ),<br>    );<br>  }<br><br>  Color _getLanguageColor(String language) {<br>    switch (language.toLowerCase()) {<br>      case &#39;dart&#39;:<br>        return Colors.blue;<br>      case &#39;javascript&#39;:<br>        return Colors.yellow[700]!;<br>      case &#39;typescript&#39;:<br>        return Colors.blue[700]!;<br>      case &#39;python&#39;:<br>        return Colors.green[700]!;<br>      case &#39;java&#39;:<br>        return Colors.orange[700]!;<br>      case &#39;kotlin&#39;:<br>        return Colors.purple[700]!;<br>      case &#39;swift&#39;:<br>        return Colors.orange[800]!;<br>      case &#39;c#&#39;:<br>        return Colors.green[800]!;<br>      case &#39;c++&#39;:<br>        return Colors.blue[800]!;<br>      default:<br>        return Colors.grey[700]!;<br>    }<br>  }<br>}</pre><h3>🔧 4️⃣ DI Layer Updates (Dependency Injection)</h3><p>To make our cubit work, we must register:</p><ul><li>Cubit</li><li>Use cases</li><li>Repository</li><li>Remote + Local data sources</li><li>Core dependencies</li><li>Isar instance</li></ul><p>This ensures our Architecture stays <strong>loosely coupled</strong> and <strong>testable</strong>.</p><h4>📂 libs/di/injection_container.dart</h4><pre>final sl = GetIt.instance;<br><br>Future&lt;void&gt; init() async {<br>  // Features - GitHub Repositories<br>  // Cubit<br>  sl.registerFactory(<br>        () =&gt; RepositoryCubit(<br>      getRepositories: sl(),<br>      refreshRepositories: sl(),<br>      getTotalCount: sl(),<br>    ),<br>  );<br><br>  // Login Feature<br>  // Cubit<br>  sl.registerFactory(<br>        () =&gt; LoginCubit(<br>      loginUseCase: sl(),<br>    ),<br>  );<br><br>  // Use cases<br>  sl.registerLazySingleton(() =&gt; GetRepositories(sl()));<br>  sl.registerLazySingleton(() =&gt; RefreshRepositories(sl()));<br>  sl.registerLazySingleton(() =&gt; GetTotalCount(sl()));<br>  sl.registerLazySingleton(() =&gt; LoginUseCase(sl()));<br><br>  // Repository<br>  sl.registerLazySingleton&lt;RepositoryRepository&gt;(<br>        () =&gt; RepositoryRepositoryImpl(<br>      remoteDataSource: sl(),<br>      localDataSource: sl(),<br>      connectionChecker: sl(),<br>    ),<br>  );<br><br>  // Data sources<br>  sl.registerLazySingleton&lt;RepositoryRemoteDataSource&gt;(<br>        () =&gt; RepositoryRemoteDataSourceImpl(dioClient: sl()),<br>  );<br>  sl.registerLazySingleton&lt;RepositoryLocalDataSource&gt;(<br>        () =&gt; RepositoryLocalDataSourceImpl(sl()),<br>  );<br><br>  // Core<br>  sl.registerLazySingleton(() =&gt; DioClient());<br>  sl.registerLazySingleton(() =&gt; InternetConnectionChecker());<br><br>  // External<br>  final dir = await getApplicationDocumentsDirectory();<br>  final isar = await Isar.open(<br>    [RepositoryModelSchema],<br>    directory: dir.path,<br>    name: DatabaseConstants.isarSchema,<br>  );<br>  sl.registerLazySingleton(() =&gt; isar);<br>}</pre><h3>🚀 Final Step — App Entry Point</h3><p>Our main.dart initializes DI and setup routing, then launches the app.</p><h4>📂 main.dart</h4><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await di.init();<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp.router( // Change to MaterialApp.router<br>      title: &#39;Flutter GitHub Repositories&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>        useMaterial3: true,<br>      ),<br>      routerConfig: appRouter, // Add this line<br>    );<br>  }<br>}</pre><h3>🎉 Conclusion — Clean Architecture in Action</h3><p>With this third and final part, our project now follows:</p><ul><li><strong>Domain Layer</strong> → Business rules</li><li><strong>Data Layer</strong> → Local + Remote + Repositories</li><li><strong>Presentation Layer</strong> → Cubit + UI</li></ul><p>You now have a fully working, scalable, testable Flutter project using:</p><p>✨ Clean Architecture<br> ✨ Cubit (BLoC) pattern<br> ✨ Isar local caching<br> ✨ Dio networking<br> ✨ Pagination + Search + Refresh<br> ✨ Dependency Injection (GetIt)</p><p>This structure is production-ready and can scale easily as your app grows.</p><blockquote><strong>Github Repository Link:</strong></blockquote><p><a href="https://github.com/Asif047/FlutterBlocCleanArchIsarPagination/tree/main">https://github.com/Asif047/FlutterBlocCleanArchIsarPagination/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd29ed505c05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Flutter Clean Architecture with BLoC & Isar — Part 2]]></title>
            <link>https://medium.com/@asifulhaque1144/flutter-clean-architecture-with-bloc-isar-part-2-26fd38215f1e?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/26fd38215f1e</guid>
            <category><![CDATA[isar-database]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[bloc-architecture]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 18:15:37 GMT</pubDate>
            <atom:updated>2025-11-05T18:15:37.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Flutter Clean Architecture with BLoC &amp; Isar — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wu_c8y11oyh0yFDD1A8Ong.png" /></figure><h3>Setting Up Config, Core, Domain &amp; Data Layer</h3><p>Welcome back to the Flutter Clean Architecture + BLoC + Isar series!<br> In <strong>Part-1</strong>, we built the project structure and talked about clean architecture fundamentals.</p><p>In <strong>Part-2</strong>, we move into actual implementation and set up:</p><p>✅ config files<br>✅ core utilities (error, network, constants, usecases)<br>✅ domain layer (entities, abstract repository, use cases)<br>✅ data layer (models, local &amp; remote datasource, repository impl)</p><h3>📂 Project Structure Recap</h3><p>Below is the folder tree for the layers we cover today:</p><pre>lib/<br> ┣ config/<br> ┃ ┗ app_router.dart<br> ┣ core/<br> ┃ ┣ error/<br> ┃ ┃ ┗ failure.dart<br> ┃ ┣ network/<br> ┃ ┃ ┗ dio_client.dart<br> ┃ ┣ usecase/<br> ┃ ┃ ┗ usecase.dart<br> ┃ ┗ util/<br> ┃   ┗ constants.dart<br> ┣ domain/<br> ┃ ┣ entities/<br> ┃ ┃ ┗ repository_entity.dart<br> ┃ ┣ repositories/<br> ┃ ┃ ┗ repository_repository.dart<br> ┃ ┗ usecase/<br> ┃   ┗ get_repositories.dart<br> ┗ data/<br>   ┣ models/<br>   ┃ ┣ repository_model.dart<br>   ┃ ┗ repository_model.g.dart (generated)<br>   ┣ datasources/<br>   ┃ ┣ local/<br>   ┃ ┃ ┗ repository_local_datasource.dart<br>   ┃ ┗ remote/<br>   ┃   ┗ repository_remote_datasource.dart<br>   ┗ repositories/<br>     ┗ repository_repository_impl.dart</pre><h3>⚙️ config/ — Application Routing</h3><p>We use <strong>GoRouter</strong> to manage app screens &amp; initial route.</p><p>config/app_router.dart</p><pre>final GoRouter appRouter = GoRouter(<br>  initialLocation: &#39;/login&#39;, // Set initial route to login page<br>  routes: [<br>    GoRoute(<br>      path: &#39;/login&#39;,<br>      builder: (context, state) =&gt; const LoginPage(),<br>    ),<br>    GoRoute(<br>      path: &#39;/home&#39;,<br>      builder: (context, state) =&gt; BlocProvider(<br>        create: (context) =&gt; sl&lt;RepositoryCubit&gt;(),<br>        child: const HomePage(),<br>      ),<br>    ),<br>  ],<br>);</pre><p>📌 <strong>Why?</strong><br> Centralized route management allows easy navigation, dependency injection, and page security later.</p><h4>🧠 Core Layer — Shared Building Blocks</h4><p>core/error/failure.dart</p><p>Handles app-wide error abstraction.</p><pre>abstract class Failure extends Equatable {<br>  final String message;<br><br>  const Failure(this.message);<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [message];<br>}<br><br>class ServerFailure extends Failure {<br>  const ServerFailure(String message) : super(message);<br>}<br><br>class CacheFailure extends Failure {<br>  const CacheFailure(String message) : super(message);<br>}<br><br>class NetworkFailure extends Failure {<br>  const NetworkFailure(String message) : super(message);<br>}</pre><blockquote>✅ Allows us to return unified failure types from any layer.</blockquote><p>core/network/dio_client.dart</p><p>Common <strong>Dio Client</strong> used across the app.</p><pre>class DioClient {<br>  final Dio _dio;<br><br>  DioClient() : _dio = Dio() {<br>    _dio.options.baseUrl = &#39;https://api.github.com&#39;;<br>    _dio.options.connectTimeout = const Duration(seconds: 10);<br>    _dio.options.receiveTimeout = const Duration(seconds: 10);<br>    _dio.options.headers = {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      &#39;Accept&#39;: &#39;application/json&#39;,<br>    };<br><br>    if (kDebugMode) {<br>      _dio.interceptors.add(LogInterceptor(<br>        requestBody: true,<br>        responseBody: true,<br>      ));<br>    }<br>  }<br><br>  Future&lt;Response&gt; get(<br>      String path, {<br>        Map&lt;String, dynamic&gt;? queryParameters,<br>        Options? options,<br>        CancelToken? cancelToken,<br>        ProgressCallback? onReceiveProgress,<br>      }) async {<br>    try {<br>      final response = await _dio.get(<br>        path,<br>        queryParameters: queryParameters,<br>        options: options,<br>        cancelToken: cancelToken,<br>        onReceiveProgress: onReceiveProgress,<br>      );<br>      return response;<br>    } catch (e) {<br>      rethrow;<br>    }<br>  }<br><br>  Future&lt;Response&gt; post(<br>      String path, {<br>        dynamic data,<br>        Map&lt;String, dynamic&gt;? queryParameters,<br>        Options? options,<br>        CancelToken? cancelToken,<br>        ProgressCallback? onSendProgress,<br>        ProgressCallback? onReceiveProgress,<br>      }) async {<br>    try {<br>      final response = await _dio.post(<br>        path,<br>        data: data,<br>        queryParameters: queryParameters,<br>        options: options,<br>        cancelToken: cancelToken,<br>        onSendProgress: onSendProgress,<br>        onReceiveProgress: onReceiveProgress,<br>      );<br>      return response;<br>    } catch (e) {<br>      rethrow;<br>    }<br>  }<br>}</pre><blockquote>✅ One centralized HTTP client, consistent configs &amp; logs.</blockquote><p>core/usecase/usecase.dart</p><pre>abstract class UseCase&lt;Type, Params&gt; {<br>  Future&lt;Either&lt;Failure, Type&gt;&gt; call(Params params);<br>}<br><br>class NoParams extends Equatable {<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class PaginationParams extends Equatable {<br>  final int page;<br>  final int perPage;<br><br>  const PaginationParams({<br>    required this.page,<br>    required this.perPage,<br>  });<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [page, perPage];<br>}</pre><blockquote>✅ Promotes abstraction — domain layer shouldn’t know UI or DB.</blockquote><p>core/util/constants.dart</p><pre>class ApiConstants {<br>  static const String baseUrl = &#39;https://api.github.com&#39;;<br>  static const String searchRepositories = &#39;/search/repositories&#39;;<br>  static const String login = &#39;https://dummyjson.com/auth/login&#39;;<br><br>  // Default parameters<br>  static const int defaultPerPage = 15;<br>  static const String defaultSearchQuery = &#39;flutter&#39;;<br>}<br><br>class DatabaseConstants {<br>  static const String isarSchema = &#39;github_repositories&#39;;<br>  static const int isarSchemaVersion = 1;<br>}<br><br>class ErrorMessages {<br>  static const String serverError = &#39;Server error occurred. Please try again later.&#39;;<br>  static const String cacheError = &#39;Cache error occurred. Please try again later.&#39;;<br>  static const String networkError = &#39;Network error occurred. Please check your connection.&#39;;<br>  static const String unknownError = &#39;Unknown error occurred. Please try again later.&#39;;<br>}</pre><p>✅ All project constants in one place makes maintenance easier.</p><h3>🏛️ Domain Layer — Pure Business Logic</h3><p><strong>Entity </strong>→ domain/entities/repository_entity.dart</p><pre>class RepositoryEntity extends Equatable {<br>  final int id;<br>  final String name;<br>  final String fullName;<br>  final String description;<br>  final String htmlUrl;<br>  final int stargazersCount;<br>  final int forksCount;<br>  final int watchersCount;<br>  final String language;<br>  final String ownerAvatarUrl;<br>  final String ownerLogin;<br><br>  const RepositoryEntity({<br>    required this.id,<br>    required this.name,<br>    required this.fullName,<br>    required this.description,<br>    required this.htmlUrl,<br>    required this.stargazersCount,<br>    required this.forksCount,<br>    required this.watchersCount,<br>    required this.language,<br>    required this.ownerAvatarUrl,<br>    required this.ownerLogin,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>    id,<br>    name,<br>    fullName,<br>    description,<br>    htmlUrl,<br>    stargazersCount,<br>    forksCount,<br>    watchersCount,<br>    language,<br>    ownerAvatarUrl,<br>    ownerLogin,<br>  ];<br>}</pre><blockquote>✅ Keeps UI independent from backend data shapes.</blockquote><p><strong>Abstract Repo</strong> → domain/repositories/repository_repository.dart</p><pre>abstract class RepositoryRepository {<br>  /// Gets a paginated list of repositories<br>  ///<br>  /// Returns a [List&lt;RepositoryEntity&gt;] on success<br>  /// Returns a [Failure] on error<br>  Future&lt;Either&lt;Failure, List&lt;RepositoryEntity&gt;&gt;&gt; getRepositories({<br>    required int page,<br>    required int perPage,<br>    String query = &#39;flutter&#39;,<br>  });<br><br>  /// Refreshes the repository data from the remote source<br>  ///<br>  /// Returns a [List&lt;RepositoryEntity&gt;] on success<br>  /// Returns a [Failure] on error<br>  Future&lt;Either&lt;Failure, List&lt;RepositoryEntity&gt;&gt;&gt; refreshRepositories({<br>    required int page,<br>    required int perPage,<br>    String query = &#39;flutter&#39;,<br>  });<br><br>  /// Returns the total count of repositories available for the given query<br>  Future&lt;Either&lt;Failure, int&gt;&gt; getTotalCount(String query);<br><br> <br>}</pre><blockquote>✅ Domain defines behavior, not implementation.</blockquote><p><strong>Use Case</strong> → domain/usecase/get_repositories.dart</p><pre>class GetRepositories implements UseCase&lt;List&lt;RepositoryEntity&gt;, RepositoryParams&gt; {<br>  final RepositoryRepository repository;<br><br>  GetRepositories(this.repository);<br><br>  @override<br>  Future&lt;Either&lt;Failure, List&lt;RepositoryEntity&gt;&gt;&gt; call(RepositoryParams params) {<br>    return repository.getRepositories(<br>      page: params.page,<br>      perPage: params.perPage,<br>      query: params.query,<br>    );<br>  }<br>}<br><br>class RefreshRepositories implements UseCase&lt;List&lt;RepositoryEntity&gt;, RepositoryParams&gt; {<br>  final RepositoryRepository repository;<br><br>  RefreshRepositories(this.repository);<br><br>  @override<br>  Future&lt;Either&lt;Failure, List&lt;RepositoryEntity&gt;&gt;&gt; call(RepositoryParams params) {<br>    return repository.refreshRepositories(<br>      page: params.page,<br>      perPage: params.perPage,<br>      query: params.query,<br>    );<br>  }<br>}<br><br>class GetTotalCount implements UseCase&lt;int, String&gt; {<br>  final RepositoryRepository repository;<br><br>  GetTotalCount(this.repository);<br><br>  @override<br>  Future&lt;Either&lt;Failure, int&gt;&gt; call(String query) {<br>    return repository.getTotalCount(query);<br>  }<br>}<br><br>class RepositoryParams extends Equatable {<br>  final int page;<br>  final int perPage;<br>  final String query;<br><br>  const RepositoryParams({<br>    required this.page,<br>    required this.perPage,<br>    this.query = &#39;flutter&#39;,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [page, perPage, query];<br>}</pre><blockquote>✅ Each action is a single unit — SOLID architecture.</blockquote><h3>💾 Data Layer — Where Logic Meets Real Data</h3><h4>Model → data/models/repository_model.dart</h4><p><em>(Includes Isar ORM)</em></p><pre>@collection<br>class RepositoryModel {<br>  Id id = Isar.autoIncrement;<br><br>  @Index(unique: true)<br>  late int repoId;<br><br>  late String name;<br>  late String fullName;<br>  late String description;<br>  late String htmlUrl;<br>  late int stargazersCount;<br>  late int forksCount;<br>  late int watchersCount;<br>  late String language;<br>  late String ownerAvatarUrl;<br>  late String ownerLogin;<br>  late int page;<br>  late String query;<br>  late DateTime cachedAt;<br><br>  RepositoryModel({<br>    required this.repoId,<br>    required this.name,<br>    required this.fullName,<br>    required this.description,<br>    required this.htmlUrl,<br>    required this.stargazersCount,<br>    required this.forksCount,<br>    required this.watchersCount,<br>    required this.language,<br>    required this.ownerAvatarUrl,<br>    required this.ownerLogin,<br>    required this.page,<br>    required this.query,<br>    required this.cachedAt,<br>  });<br><br>  factory RepositoryModel.fromJson(Map&lt;String, dynamic&gt; json, {required int page, required String query}) {<br>    final owner = json[&#39;owner&#39;] ?? {};<br><br>    return RepositoryModel(<br>      repoId: json[&#39;id&#39;] ?? 0,<br>      name: json[&#39;name&#39;] ?? &#39;&#39;,<br>      fullName: json[&#39;full_name&#39;] ?? &#39;&#39;,<br>      description: json[&#39;description&#39;] ?? &#39;&#39;,<br>      htmlUrl: json[&#39;html_url&#39;] ?? &#39;&#39;,<br>      stargazersCount: json[&#39;stargazers_count&#39;] ?? 0,<br>      forksCount: json[&#39;forks_count&#39;] ?? 0,<br>      watchersCount: json[&#39;watchers_count&#39;] ?? 0,<br>      language: json[&#39;language&#39;] ?? &#39;Unknown&#39;,<br>      ownerAvatarUrl: owner[&#39;avatar_url&#39;] ?? &#39;&#39;,<br>      ownerLogin: owner[&#39;login&#39;] ?? &#39;&#39;,<br>      page: page,<br>      query: query,<br>      cachedAt: DateTime.now(),<br>    );<br>  }<br><br>  RepositoryEntity toEntity() {<br>    return RepositoryEntity(<br>      id: repoId,<br>      name: name,<br>      fullName: fullName,<br>      description: description,<br>      htmlUrl: htmlUrl,<br>      stargazersCount: stargazersCount,<br>      forksCount: forksCount,<br>      watchersCount: watchersCount,<br>      language: language,<br>      ownerAvatarUrl: ownerAvatarUrl,<br>      ownerLogin: ownerLogin,<br>    );<br>  }<br><br>  factory RepositoryModel.fromEntity(RepositoryEntity entity, {required int page, required String query}) {<br>    return RepositoryModel(<br>      repoId: entity.id,<br>      name: entity.name,<br>      fullName: entity.fullName,<br>      description: entity.description,<br>      htmlUrl: entity.htmlUrl,<br>      stargazersCount: entity.stargazersCount,<br>      forksCount: entity.forksCount,<br>      watchersCount: entity.watchersCount,<br>      language: entity.language,<br>      ownerAvatarUrl: entity.ownerAvatarUrl,<br>      ownerLogin: entity.ownerLogin,<br>      page: page,<br>      query: query,<br>      cachedAt: DateTime.now(),<br>    );<br>  }<br>}</pre><blockquote>✅ Converts API/DB data ↔ domain entities.</blockquote><p><strong>Local DB</strong> → repository_local_datasource.dart</p><pre>abstract class RepositoryLocalDataSource {<br>  /// Gets repositories from the local cache<br>  Future&lt;List&lt;RepositoryModel&gt;&gt; getRepositories({<br>    required int page,<br>    required String query,<br>  });<br><br>  /// Caches repositories in the local database<br>  Future&lt;void&gt; cacheRepositories(List&lt;RepositoryModel&gt; repositories);<br><br>  /// Clears all cached repositories for a specific query<br>  Future&lt;void&gt; clearCache(String query);<br><br>  /// Returns the total count of repositories available for a given query<br>  Future&lt;int&gt; getTotalCount(String query);<br><br>  /// Checks if cache exists for the given page and query<br>  Future&lt;bool&gt; hasCacheForPage({<br>    required int page,<br>    required String query,<br>  });<br>}<br><br>class RepositoryLocalDataSourceImpl implements RepositoryLocalDataSource {<br>  final Isar _db;<br><br>  RepositoryLocalDataSourceImpl(this._db);<br><br>  @override<br>  Future&lt;List&lt;RepositoryModel&gt;&gt; getRepositories({<br>    required int page,<br>    required String query,<br>  }) async {<br>    return _db.repositoryModels<br>        .filter()<br>        .pageEqualTo(page)<br>        .and()<br>        .queryEqualTo(query)<br>        .findAll();<br>  }<br><br>  @override<br>  Future&lt;void&gt; cacheRepositories(List&lt;RepositoryModel&gt; repositories) async {<br>    await _db.writeTxn(() async {<br>      await _db.repositoryModels.putAll(repositories);<br>    });<br>  }<br><br>  @override<br>  Future&lt;void&gt; clearCache(String query) async {<br>    await _db.writeTxn(() async {<br>      await _db.repositoryModels<br>          .filter()<br>          .queryEqualTo(query)<br>          .deleteAll();<br>    });<br>  }<br><br>  @override<br>  Future&lt;int&gt; getTotalCount(String query) async {<br>    return _db.repositoryModels<br>        .filter()<br>        .queryEqualTo(query)<br>        .count();<br>  }<br><br>  @override<br>  Future&lt;bool&gt; hasCacheForPage({<br>    required int page,<br>    required String query,<br>  }) async {<br>    final count = await _db.repositoryModels<br>        .filter()<br>        .pageEqualTo(page)<br>        .and()<br>        .queryEqualTo(query)<br>        .count();<br><br>    return count &gt; 0;<br>  }<br>}</pre><blockquote>✅ Handles caching using <strong>Isar</strong> database.</blockquote><p><strong>Remote API </strong>→ repository_remote_datasource.dart</p><pre>abstract class RepositoryRemoteDataSource {<br>  /// Gets repositories from the remote API<br>  ///<br>  /// Throws a [ServerFailure] if there is a server error<br>  Future&lt;List&lt;RepositoryModel&gt;&gt; getRepositories({<br>    required int page,<br>    required int perPage,<br>    required String query,<br>  });<br><br>  /// Gets total count of repositories for a query<br>  Future&lt;int&gt; getTotalCount(String query);<br><br>  /// Logs in a user<br>  Future&lt;UserModel&gt; login({<br>    required String username,<br>    required String password,<br>  });<br>}<br><br>class RepositoryRemoteDataSourceImpl implements RepositoryRemoteDataSource {<br>  final DioClient dioClient;<br><br>  RepositoryRemoteDataSourceImpl({required this.dioClient});<br><br>  @override<br>  Future&lt;List&lt;RepositoryModel&gt;&gt; getRepositories({<br>    required int page,<br>    required int perPage,<br>    required String query,<br>  }) async {<br>    try {<br>      final response = await dioClient.get(<br>        ApiConstants.searchRepositories,<br>        queryParameters: {<br>          &#39;q&#39;: query,<br>          &#39;page&#39;: page,<br>          &#39;per_page&#39;: perPage,<br>        },<br>      );<br><br>      if (response.statusCode == 200) {<br>        final List&lt;dynamic&gt; items = response.data[&#39;items&#39;];<br>        return items<br>            .map((item) =&gt; RepositoryModel.fromJson(item, page: page, query: query))<br>            .toList();<br>      } else {<br>        throw const ServerFailure(ErrorMessages.serverError);<br>      }<br>    } on DioException catch (e) {<br>      throw ServerFailure(e.message ?? ErrorMessages.serverError);<br>    } catch (e) {<br>      throw const ServerFailure(ErrorMessages.unknownError);<br>    }<br>  }<br><br>  @override<br>  Future&lt;int&gt; getTotalCount(String query) async {<br>    try {<br>      final response = await dioClient.get(<br>        ApiConstants.searchRepositories,<br>        queryParameters: {<br>          &#39;q&#39;: query,<br>          &#39;page&#39;: 1,<br>          &#39;per_page&#39;: 1,<br>        },<br>      );<br><br>      if (response.statusCode == 200) {<br>        return response.data[&#39;total_count&#39;] ?? 0;<br>      } else {<br>        throw const ServerFailure(ErrorMessages.serverError);<br>      }<br>    } on DioException catch (e) {<br>      throw ServerFailure(e.message ?? ErrorMessages.serverError);<br>    } catch (e) {<br>      throw const ServerFailure(ErrorMessages.unknownError);<br>    }<br>  }</pre><blockquote>✅ Makes network calls with Dio.</blockquote><p><strong>Repository Impl</strong> → repository_repository_impl.dart</p><pre>class RepositoryRepositoryImpl implements RepositoryRepository {<br>  final RepositoryRemoteDataSource remoteDataSource;<br>  final RepositoryLocalDataSource localDataSource;<br>  final InternetConnectionChecker connectionChecker;<br><br>  RepositoryRepositoryImpl({<br>    required this.remoteDataSource,<br>    required this.localDataSource,<br>    required this.connectionChecker,<br>  });<br><br>  @override<br>  Future&lt;Either&lt;Failure, List&lt;RepositoryEntity&gt;&gt;&gt; getRepositories({<br>    required int page,<br>    required int perPage,<br>    String query = &#39;flutter&#39;,<br>  }) async {<br>    try {<br>      // Check if we have cache for this page and query<br>      final hasCache = await localDataSource.hasCacheForPage(<br>        page: page,<br>        query: query,<br>      );<br><br>      if (hasCache) {<br>        // Return from cache if available<br>        final cachedRepositories = await localDataSource.getRepositories(<br>          page: page,<br>          query: query,<br>        );<br><br>        return Right(cachedRepositories.map((model) =&gt; model.toEntity()).toList());<br>      }<br><br>      // No cache, check for internet connection<br>      if (!(await connectionChecker.hasConnection)) {<br>        return const Left(NetworkFailure(ErrorMessages.networkError));<br>      }<br><br>      // Fetch from remote and cache<br>      final repositories = await remoteDataSource.getRepositories(<br>        page: page,<br>        perPage: perPage,<br>        query: query,<br>      );<br><br>      await localDataSource.cacheRepositories(repositories);<br><br>      return Right(repositories.map((model) =&gt; model.toEntity()).toList());<br>    } on ServerFailure catch (e) {<br>      return Left(e);<br>    } catch (e) {<br>      return Left(CacheFailure(e.toString()));<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, List&lt;RepositoryEntity&gt;&gt;&gt; refreshRepositories({<br>    required int page,<br>    required int perPage,<br>    String query = &#39;flutter&#39;,<br>  }) async {<br>    try {<br>      if (!(await connectionChecker.hasConnection)) {<br>        return const Left(NetworkFailure(ErrorMessages.networkError));<br>      }<br><br>      // Clear cache for this query<br>      if (page == 1) {<br>        await localDataSource.clearCache(query);<br>      }<br><br>      // Fetch fresh data<br>      final repositories = await remoteDataSource.getRepositories(<br>        page: page,<br>        perPage: perPage,<br>        query: query,<br>      );<br><br>      // Cache new data<br>      await localDataSource.cacheRepositories(repositories);<br><br>      return Right(repositories.map((model) =&gt; model.toEntity()).toList());<br>    } on ServerFailure catch (e) {<br>      return Left(e);<br>    } catch (e) {<br>      return Left(CacheFailure(e.toString()));<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, int&gt;&gt; getTotalCount(String query) async {<br>    try {<br>      if (await connectionChecker.hasConnection) {<br>        // Try to get from remote<br>        return Right(await remoteDataSource.getTotalCount(query));<br>      } else {<br>        // Fallback to local count<br>        return Right(await localDataSource.getTotalCount(query));<br>      }<br>    } on ServerFailure catch (e) {<br>      return Left(e);<br>    } catch (e) {<br>      return Left(CacheFailure(e.toString()));<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, UserEntity&gt;&gt; login({<br>    required String username,<br>    required String password,<br>  }) async {<br>    try {<br>      if (!(await connectionChecker.hasConnection)) {<br>        return const Left(NetworkFailure(ErrorMessages.networkError));<br>      }<br><br>      final UserModel userModel = await remoteDataSource.login(<br>        username: username,<br>        password: password,<br>      );<br>      return Right(userModel);<br>    } on ServerFailure catch (e) {<br>      return Left(e);<br>    } catch (e) {<br>      return Left(ServerFailure(e.toString()));<br>    }<br>  }<br>}</pre><blockquote>✅ Orchestrates between API, Cache, and connectivity.</blockquote><p>🎯 <strong>Summary </strong>— What We Achieved Today</p><pre>| Layer  | Purpose                                             |<br>| ------ | --------------------------------------------------- |<br>| Config | Central route management                            |<br>| Core   | Shared utilities (Dio, failure, constants, usecase) |<br>| Domain | Pure business logic &amp; abstraction                   |<br>| Data   | Real implementation with API + Isar cache           |</pre><p>We now have a <strong>fully decoupled data pipeline</strong> in place.</p><h3>✅ Up Next — Part-3 Preview</h3><p>In <strong>Part-3</strong>, we will:</p><ul><li>Build Presentation layer</li><li>Add Cubit + BLoC States</li><li>Build UI Screens (Login, Home)</li><li>Inject Dependencies via get_it</li></ul><p>📌 <strong>This is where everything connects!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26fd38215f1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Flutter Clean Architecture with BLoC & Isar — Part 1]]></title>
            <link>https://medium.com/@asifulhaque1144/flutter-clean-architecture-with-bloc-isar-part-1-c59364dea046?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/c59364dea046</guid>
            <category><![CDATA[isar-database]]></category>
            <category><![CDATA[bloc-architecture]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 16:43:08 GMT</pubDate>
            <atom:updated>2025-11-04T16:43:08.373Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Flutter Clean Architecture with BLoC &amp; Isar — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEu2qe9PBCMizg1JyzCxJg.png" /></figure><p><em>A Practical Guide to Building a GitHub Repository List App (with Offline Support)</em></p><p>When it comes to building scalable production-ready mobile apps, maintaining a clean architecture and predictable state management is essential. In this 3-part series, we will build a Flutter app that fetches GitHub repository data using an API, displays it using <strong>BLoC / Cubit</strong>, and caches responses locally with <strong>Isar Database</strong> for offline access.</p><p>In this <strong>Part-1</strong>, we focus on:</p><p>✅ Setting up our Clean Architecture structure<br> ✅ Adding required packages<br> ✅ Understanding project layers (Domain → Data → Presentation)<br> ✅ Preparing project folder structure</p><p>By the end of this series, you will have a fully working app that:</p><ul><li>Fetches GitHub repositories via API (using <strong>Dio</strong>)</li><li>Stores data in <strong>Isar local database</strong></li><li>Follows <strong>Clean Architecture</strong></li><li>Uses <strong>BLoC / Cubit</strong> for state management</li><li>Uses <strong>Get_it</strong> for dependency injection</li></ul><h3>🏗️ Clean Architecture + BLoC = Maintainability ❤️</h3><p>We will follow the classical clean architectural approach:</p><blockquote><strong><em>Presentation → Domain → Data</em></strong></blockquote><p>Where each layer has a single responsibility and does not depend directly on lower layers.</p><pre>lib/<br> ├── config/<br> ├── core/<br> ├── data/<br> ├── di/<br> ├── domain/<br> ├── presentation/<br> └── main.dart</pre><p>This keeps the project clean, scalable, and testable. Let’s walk through each section 👇</p><h3>📦 Step 1 — pubspec.yaml (Project Dependencies)</h3><p>We will be using:</p><ul><li><strong>flutter_bloc</strong> → State Management</li><li><strong>Dio</strong> → API client</li><li><strong>Isar</strong> → NoSQL local database</li><li><strong>Get_it</strong> → Dependency injection</li><li><strong>Dartz</strong> → Functional error handling</li><li><strong>Go Router</strong> → Navigation</li><li><strong>json_serializable</strong> → Auto model generation</li></ul><p>Here’s the pubspec.yaml we are working with:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  cupertino_icons: ^1.0.8<br><br>  # BLoC / Cubit<br>  flutter_bloc: ^8.1.3<br>  equatable: ^2.0.5<br><br>  # Network<br>  dio: ^5.3.3<br>  internet_connection_checker: ^1.0.0+1<br><br>  # Local Database<br>  isar: ^3.1.0<br>  path_provider: ^2.1.1<br>  json_annotation: ^4.9.0<br><br>  # Dependency Injection<br>  get_it: ^7.6.4<br><br>  # Utils<br>  dartz: ^0.10.1<br>  intl: ^0.18.1<br>  go_router: ^13.2.0</pre><p>And our dev tools:</p><pre>dev_dependencies:<br>  build_runner: ^2.4.6<br>  isar_generator: ^3.1.0<br>  json_serializable: ^6.7.1<br>  flutter_lints: ^5.0.0</pre><h3>📂 Step 2 — Folder Structure</h3><p>Below is the architecture breakdown we will build in this series:</p><p>✅ config/</p><blockquote><em>App-wide router and configuration</em></blockquote><pre>config/<br> └── app_router.dart</pre><p>✅ core/</p><blockquote><em>Common utilities &amp; shared logic</em></blockquote><pre>core/error/failure.dart<br>core/network/dio_client.dart<br>core/usecase/usecase.dart<br>core/util/constants.dart</pre><p>✅ data layer</p><blockquote><em>Contains models, datasources, repository implementation</em></blockquote><pre>data/datasources/local/repository_local_datasource.dart<br>data/datasources/remote/repository_remote_datasource.dart<br><br>data/models/repository_model.dart<br>data/models/repository_model.g.dart<br><br>data/repositories/repository_repository_impl.dart</pre><p>✅ di/ — Dependency Injection</p><pre>di/injection_container.dart</pre><p>✅ domain layer</p><blockquote><em>Pure business logic — no Flutter imports!</em></blockquote><pre>domain/entities/repository_entity.dart<br>domain/repositories/repository_repository.dart<br>domain/usecase/get_repositories.dart</pre><p>✅ presentation layer — BLoC + UI</p><pre>presentation/cubit/repository_cubit.dart<br>presentation/cubit/repository_state.dart<br><br>presentation/pages/home_page.dart<br>presentation/widgets/repository_list_item.dart</pre><p>✅ Entry Point</p><pre>lib/main.dart</pre><h3>📂 Complete Folder Structure (Reference Tree)</h3><p>Below is the full folder structure we are following in this project 👇</p><pre>lib/<br>├── config/<br>│   └── app_router.dart<br>│<br>├── core/<br>│   ├── error/<br>│   │   └── failure.dart<br>│   ├── network/<br>│   │   └── dio_client.dart<br>│   ├── usecase/<br>│   │   └── usecase.dart<br>│   └── util/<br>│       └── constants.dart<br>│<br>├── data/<br>│   ├── datasources/<br>│   │   ├── local/<br>│   │   │   └── repository_local_datasource.dart<br>│   │   └── remote/<br>│   │       └── repository_remote_datasource.dart<br>│   │<br>│   ├── models/<br>│   │   ├── repository_model.dart<br>│   │   └── repository_model.g.dart<br>│   │<br>│   └── repositories/<br>│       └── repository_repository_impl.dart<br>│<br>├── di/<br>│   └── injection_container.dart<br>│<br>├── domain/<br>│   ├── entities/<br>│   │   └── repository_entity.dart<br>│   ├── repositories/<br>│   │   └── repository_repository.dart<br>│   └── usecase/<br>│       └── get_repositories.dart<br>│<br>├── presentation/<br>│   ├── cubit/<br>│   │   ├── repository_cubit.dart<br>│   │   └── repository_state.dart<br>│   │<br>│   ├── pages/<br>│   │   └── home_page.dart<br>│   │<br>│   └── widgets/<br>│       └── repository_list_item.dart<br>│<br>└── main.dart</pre><h3>🎯 Wrapping Up Part-1</h3><p>✅ Set up Clean Architecture<br> ✅ Installed &amp; explained dependencies<br> ✅ Created project structure<br> ✅ Shared complete folder tree</p><p>Next in <strong>Part-2</strong>, we will:</p><ul><li>Create Entity + Model (Isar + JSON)</li><li>Write Repository + UseCase</li><li>Implement Local &amp; Remote Data Sources</li><li>Set up Dio client &amp; Isar database</li></ul><blockquote><em>This is where the real implementation starts 💪🔥</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c59364dea046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Flutter GetX State Management — Integrate API and Display User List (Part II)]]></title>
            <link>https://medium.com/@asifulhaque1144/flutter-getx-state-management-integrate-api-and-display-user-list-part-ii-a7d4e80790ce?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d4e80790ce</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[rest-api-call]]></category>
            <category><![CDATA[getx]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 18:12:08 GMT</pubDate>
            <atom:updated>2025-10-28T18:16:00.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjbDwIP2hTCIQU9Y5J5IuQ.png" /></figure><h3>🚀 Flutter GetX State Management — Integrate API and Display User List (Part II)</h3><p>Welcome back to the second part of our <strong>Flutter GetX State Management</strong> tutorial series! 🎉</p><p>In the <a href="https://medium.com/@asifulhaque1144/flutter-getx-state-management-integrate-api-and-display-user-list-4884327b8dfd">previous part (Part I)</a>, we set up our <strong>project structure</strong>, added the <strong>necessary dependencies</strong>, and built a <strong>solid API layer</strong> using <strong>Dio</strong>, <strong>GetX</strong>, and <strong>Dartz</strong> for error handling.</p><p>Now, in this second part, we’ll complete the setup by:<br> ✅ Creating our <strong>Controller</strong> using GetX<br> ✅ Building the <strong>View (UI)</strong> to display the user list<br> ✅ Setting up <strong>Bindings</strong> for dependency injection<br> ✅ Adding <strong>routes</strong> for navigation between screens</p><p>By the end of this post, you’ll have a <strong>fully functional user list screen</strong> powered by GetX, complete with state management, dependency injection, and reactive UI updates.</p><h3>🧠 Step 1: Create the Controller — user_controller.dart</h3><p>The <strong>Controller</strong> in GetX is the heart of your app’s state management.<br> It interacts with the repository layer, fetches data, and updates the UI reactively using <strong>Rx variables</strong>.</p><p>📁 <strong>Path:</strong> modules/users/controllers/user_controller.dart</p><pre>class UserController extends GetxController {<br>  final UserRepository _userRepository;<br><br>  UserController(this._userRepository);<br><br>  final RxList&lt;User&gt; users = &lt;User&gt;[].obs;<br>  final RxBool isLoading = false.obs;<br>  final RxString errorMessage = &#39;&#39;.obs;<br>  final Rx&lt;User?&gt; selectedUser = Rx&lt;User?&gt;(null);<br><br>  @override<br>  void onInit() {<br>    super.onInit();<br>    fetchUsers();<br>  }<br><br>  Future&lt;void&gt; fetchUsers() async {<br>    isLoading.value = true;<br>    final result = await _userRepository.getUsers();<br>    result.fold(<br>      (error) {<br>        errorMessage.value = error.message;<br>        Get.snackbar(&#39;Error&#39;, error.message);<br>      },<br>      (userList) =&gt; users.assignAll(userList),<br>    );<br>    isLoading.value = false;<br>  }<br><br>  Future&lt;void&gt; fetchUserById(int id) async {<br>    isLoading.value = true;<br>    final result = await _userRepository.getUserById(id);<br>    result.fold(<br>      (error) {<br>        errorMessage.value = error.message;<br>        Get.snackbar(&#39;Error&#39;, error.message);<br>      },<br>      (user) =&gt; selectedUser.value = user,<br>    );<br>    isLoading.value = false;<br>  }<br><br>  void selectUser(User user) {<br>    selectedUser.value = user;<br>  }<br><br>  void refreshUsers() {<br>    fetchUsers();<br>  }<br>}</pre><p>Here’s what’s happening:</p><ul><li>RxList, RxBool, and RxString make the variables <strong>observable</strong>.</li><li>The controller calls fetchUsers() inside onInit(), which automatically runs when the controller is initialized.</li><li>Error handling and loading states are managed reactively using GetX’s built-in tools like Get.snackbar.</li></ul><h3>⚙️ Step 2: Add the Initial Binding — initial_binding.dart</h3><p>Bindings in GetX help manage <strong>dependency injection</strong> automatically.<br> Instead of manually initializing objects, GetX handles it for you — ensuring your app stays modular and testable.</p><p>📁 <strong>Path:</strong> bindings/initial_binding.dart</p><pre>class InitialBinding extends Bindings {<br>  @override<br>  void dependencies() {<br>    Get.lazyPut&lt;DioClient&gt;(() =&gt; DioClient());<br>    Get.lazyPut&lt;ApiProvider&gt;(() =&gt; ApiProvider(Get.find()));<br>    Get.lazyPut&lt;UserRepository&gt;(() =&gt; UserRepository(Get.find()));<br>    Get.lazyPut&lt;UserController&gt;(() =&gt; UserController(Get.find()));<br>  }<br>}</pre><p>💡 Using Get.lazyPut() ensures that the object is created <strong>only when it’s needed</strong>, optimizing memory usage and app performance.</p><h3>🖼️ Step 3: Build the User List View — user_list_view.dart</h3><p>Now comes the fun part — building the <strong>UI</strong> for our user list!<br> This screen listens to the reactive state variables from the controller and updates automatically when the data changes.</p><p>📁 <strong>Path:</strong> modules/users/views/user_list_view.dart</p><pre>class UserListView extends GetView&lt;UserController&gt; {<br>  const UserListView({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: CustomAppBar(<br>        title: &#39;Users&#39;,<br>        actions: [<br>          IconButton(<br>            icon: const Icon(Icons.refresh),<br>            onPressed: () =&gt; controller.refreshUsers(),<br>          ),<br>        ],<br>      ),<br>      body: Obx(() {<br>        if (controller.isLoading.value &amp;&amp; controller.users.isEmpty) {<br>          return const LoadingWidget();<br>        }<br><br>        if (controller.errorMessage.isNotEmpty &amp;&amp; controller.users.isEmpty) {<br>          return Center(<br>            child: Column(<br>              mainAxisAlignment: MainAxisAlignment.center,<br>              children: [<br>                Icon(Icons.error_outline, size: 64, color: Colors.red[300]),<br>                const SizedBox(height: 16),<br>                Text(&#39;Error loading users&#39;, style: Theme.of(context).textTheme.headlineSmall),<br>                const SizedBox(height: 8),<br>                Padding(<br>                  padding: const EdgeInsets.symmetric(horizontal: 32),<br>                  child: Text(<br>                    controller.errorMessage.value,<br>                    textAlign: TextAlign.center,<br>                    style: Theme.of(context).textTheme.bodyMedium,<br>                  ),<br>                ),<br>                const SizedBox(height: 16),<br>                ElevatedButton(<br>                  onPressed: () =&gt; controller.refreshUsers(),<br>                  child: const Text(&#39;Retry&#39;),<br>                ),<br>              ],<br>            ),<br>          );<br>        }<br><br>        return RefreshIndicator(<br>          onRefresh: () async =&gt; controller.refreshUsers(),<br>          child: ListView.builder(<br>            padding: const EdgeInsets.all(16),<br>            itemCount: controller.users.length,<br>            itemBuilder: (context, index) {<br>              final user = controller.users[index];<br>              return UserCard(<br>                user: user,<br>                onTap: () {<br>                  controller.selectUser(user);<br>                  Get.toNamed(Routes.USER_DETAIL);<br>                },<br>              );<br>            },<br>          ),<br>        );<br>      }),<br>    );<br>  }<br>}</pre><p>✨ Obx() is the magic that makes GetX reactive — it automatically rebuilds the UI when observable variables change!</p><h3>🧩 Step 4: Create Reusable Widgets</h3><p>To keep our UI modular and maintainable, let’s separate the reusable parts into the widgets directory.</p><p>1️⃣ widgets/custom_app_bar.dart</p><pre>class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {<br>  final String title;<br>  final List&lt;Widget&gt;? actions;<br>  final bool showBackButton;<br><br>  const CustomAppBar({<br>    Key? key,<br>    required this.title,<br>    this.actions,<br>    this.showBackButton = false,<br>  }) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AppBar(<br>      title: Text(title),<br>      leading: showBackButton<br>          ? IconButton(<br>              icon: const Icon(Icons.arrow_back),<br>              onPressed: () =&gt; Get.back(),<br>            )<br>          : null,<br>      actions: actions,<br>    );<br>  }<br><br>  @override<br>  Size get preferredSize =&gt; const Size.fromHeight(kToolbarHeight);<br>}</pre><p>2️⃣ widgets/loading_widget.dart</p><p>A shimmer-based loading effect while fetching users 👇</p><pre>class LoadingWidget extends StatelessWidget {<br>  const LoadingWidget({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ListView.builder(<br>      padding: const EdgeInsets.all(16),<br>      itemCount: 10,<br>      itemBuilder: (context, index) {<br>        return Card(<br>          margin: const EdgeInsets.only(bottom: 12),<br>          child: Shimmer.fromColors(<br>            baseColor: Colors.grey[300]!,<br>            highlightColor: Colors.grey[100]!,<br>            child: ListTile(<br>              contentPadding: const EdgeInsets.all(16),<br>              leading: CircleAvatar(backgroundColor: Colors.grey[300]),<br>              title: Container(<br>                height: 16,<br>                decoration: BoxDecoration(<br>                  color: Colors.grey[300],<br>                  borderRadius: BorderRadius.circular(4),<br>                ),<br>              ),<br>              subtitle: Column(<br>                crossAxisAlignment: CrossAxisAlignment.start,<br>                children: [<br>                  const SizedBox(height: 8),<br>                  Container(height: 12, width: 200, color: Colors.grey[300]),<br>                  const SizedBox(height: 4),<br>                  Container(height: 12, width: 150, color: Colors.grey[300]),<br>                ],<br>              ),<br>            ),<br>          ),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>3️⃣ widgets/user_card.dart</p><p>Each user’s card UI is extracted as a reusable widget 👇</p><pre>class UserCard extends StatelessWidget {<br>  final User user;<br>  final VoidCallback onTap;<br><br>  const UserCard({<br>    super.key,<br>    required this.user,<br>    required this.onTap,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Card(<br>      margin: const EdgeInsets.only(bottom: 12),<br>      child: ListTile(<br>        contentPadding: const EdgeInsets.all(16),<br>        leading: CircleAvatar(<br>          backgroundColor: Colors.blue,<br>          child: Text(<br>            user.name.substring(0, 1).toUpperCase(),<br>            style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),<br>          ),<br>        ),<br>        title: Text(user.name, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),<br>        subtitle: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: [<br>            const SizedBox(height: 4),<br>            Text(user.email, style: const TextStyle(color: Colors.grey)),<br>            const SizedBox(height: 2),<br>            Text(user.company.name, style: const TextStyle(color: Colors.blue, fontSize: 12)),<br>          ],<br>        ),<br>        trailing: const Icon(Icons.arrow_forward_ios, size: 16),<br>        onTap: onTap,<br>      ),<br>    );<br>  }<br>}</pre><h3>🧭 Step 5: Setup Routing — app_pages.dart and app_routes.dart</h3><p>Finally, let’s define the app’s navigation system using GetX routes.</p><p>📁 <strong>Path:</strong> routes/app_pages.dart</p><pre>class AppPages {<br>  static const INITIAL = Routes.LOGIN;<br><br>  static final routes = [<br>    GetPage(<br>      name: Routes.USER_LIST,<br>      page: () =&gt; const UserListView(),<br>      binding: BindingsBuilder(() {<br>        Get.lazyPut&lt;UserController&gt;(() =&gt; UserController(Get.find()));<br>      }),<br>    ),<br>    GetPage(<br>      name: Routes.USER_DETAIL,<br>      page: () =&gt; const UserDetailView(),<br>    ),<br>    GetPage(<br>      name: Routes.LOGIN,<br>      page: () =&gt; const LoginView(),<br>      binding: LoginBinding(),<br>    ),<br>  ];<br>}</pre><p>📁 <strong>Path:</strong> routes/app_routes.dart</p><pre>abstract class Routes {<br>  static const USER_LIST = &#39;/users&#39;;<br>  static const USER_DETAIL = &#39;/user-detail&#39;;<br>  static const LOGIN = &#39;/login&#39;;<br>}</pre><p>And at last, this is how we need to modify our main.dart file:</p><blockquote>main.dart</blockquote><pre>void main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return GetMaterialApp(<br>      title: &#39;Flutter GetX App&#39;,<br>      theme: AppTheme.lightTheme,<br>      initialBinding: InitialBinding(),<br>      initialRoute: AppPages.INITIAL,<br>      getPages: AppPages.routes,<br>      debugShowCheckedModeBanner: false,<br>    );<br>  }<br>}</pre><h3>🎯 Wrapping Up</h3><p>In this part, we completed our <strong>GetX state management setup</strong> by:</p><ul><li>Creating a <strong>controller</strong> to manage data flow</li><li>Building a <strong>reactive UI</strong> using Obx()</li><li>Separating widgets for clean architecture</li><li>Adding <strong>dependency injection and routing</strong></li></ul><p>With this, your app can now <strong>fetch and display users dynamically</strong> from the API with a clean, reactive, and scalable architecture.</p><p>Github link of the project:<br><a href="https://github.com/Asif047/flutter_getx_api_call">https://github.com/Asif047/flutter_getx_api_call</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d4e80790ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Flutter GetX State Management — Integrate API and Display User List]]></title>
            <link>https://medium.com/@asifulhaque1144/flutter-getx-state-management-integrate-api-and-display-user-list-4884327b8dfd?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/4884327b8dfd</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[getx]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 18:19:52 GMT</pubDate>
            <atom:updated>2025-10-26T18:20:25.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjbDwIP2hTCIQU9Y5J5IuQ.png" /></figure><h3>🚀 Flutter GetX State Management — Integrate API and Display User List (Part- I)</h3><p>When building Flutter applications, managing state effectively while keeping the code clean and scalable can be challenging. That’s where <strong>GetX</strong> comes in — a lightweight yet powerful state management solution that also handles dependency injection and route management out of the box.</p><p>In this article, we’ll walk through a <strong>complete example of integrating a REST API using GetX</strong> to fetch a <strong>list of users</strong> and display it beautifully on the screen.</p><p>By the end of this tutorial, you’ll understand how to structure your Flutter project in a modular way, separate responsibilities (like API handling, data management, and UI), and use GetX effectively for <strong>reactive and maintainable architecture</strong>.</p><p>Let’s get started! 💪</p><h3>🧭 Project Folder Structure Overview</h3><p>Before diving into the code, here’s the overall folder structure we’ll be following.<br> Organizing your Flutter app this way helps maintain clarity, separation of concerns, and scalability for larger projects.</p><pre>lib/<br>│<br>├── app/<br>│   ├── bindings/<br>│   │   └── initial_bindings.dart<br>│   │<br>│   ├── core/<br>│   │   ├── constants/<br>│   │   │   └── api_constants.dart<br>│   │   └── theme/<br>│   │       └── app_theme.dart<br>│   │<br>│   ├── data/<br>│   │   ├── models/<br>│   │   │   ├── responses/<br>│   │   │   │   ├── api_response.dart<br>│   │   │   │   └── error_response.dart<br>│   │   │   ├── user_model.dart<br>│   │   │   └── user_model.g.dart<br>│   │   │<br>│   │   ├── providers/<br>│   │   │   ├── api_provider.dart<br>│   │   │   └── dio_client.dart<br>│   │   │<br>│   │   └── repositories/<br>│   │       └── user_repository.dart<br>│   │<br>│   ├── module/<br>│   │   └── user/<br>│   │       ├── controllers/<br>│   │       │   └── user_controller.dart<br>│   │       └── views/<br>│   │           └── user_list_view.dart<br>│   │<br>│   ├── routes/<br>│   │   ├── app_pages.dart<br>│   │   └── app_routes.dart<br>│   │<br>│   ├── widgets/<br>│   │   ├── custom_app_bar.dart<br>│   │   ├── loading_widget.dart<br>│   │   └── user_card.dart<br>│   │<br>│   └── main.dart<br>│<br>└── pubspec.yaml</pre><h3>🧱 Step 1: Setting Up Dependencies in pubspec.yaml</h3><p>Before we dive into GetX, let’s first add all the necessary packages to our project.<br> Open your pubspec.yaml file and make sure it includes the following dependencies 👇</p><pre>name: flutter_getx_api_call<br>description: &quot;A new Flutter project.&quot;<br>publish_to: &#39;none&#39;<br><br>version: 1.0.0+1<br><br>environment:<br>  sdk: ^3.7.2<br><br>dependencies:<br>  flutter:<br>    sdk: flutter<br><br>  # GetX for state management, navigation, and dependency injection<br>  get: ^4.6.6<br><br>  # HTTP clients<br>  http: ^1.1.0<br>  dio: ^5.4.0<br><br>  # Functional programming utilities (Either, Option, etc.)<br>  dartz: ^0.10.1<br><br>  # JSON serialization<br>  json_annotation: ^4.8.1<br><br>  # Cached network images and shimmer effects<br>  cached_network_image: ^3.3.0<br>  shimmer: ^3.0.0<br><br>  # Cupertino icons<br>  cupertino_icons: ^1.0.8<br><br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  json_serializable: ^6.7.1<br>  build_runner: ^2.4.7<br>  flutter_lints: ^5.0.0<br><br>flutter:<br>  uses-material-design: true</pre><p>✅ <strong>Explanation:</strong></p><ul><li><strong>GetX</strong> — handles state management, routing, and dependency injection effortlessly.</li><li><strong>Dio</strong> — a robust HTTP client for making API calls with interceptors and configurations.</li><li><strong>Dartz</strong> — provides functional programming tools like Either for clean API response handling.</li><li><strong>Json Serializable</strong> — simplifies JSON serialization and model generation.</li><li><strong>Cached Network Image</strong> &amp; <strong>Shimmer</strong> — improve image loading performance and add placeholders.</li></ul><p>Once you’ve saved your file, run:</p><pre>flutter pub get</pre><h3>🧩 Step 2: Setting Up the Core Package</h3><p>After installing dependencies, let’s organize our <strong>core setup</strong>.<br> This layer includes constants and theming — things that are shared across the app.</p><p>🔹 core/constants/api_constants.dart</p><p>We’ll keep all our API endpoints and configurations centralized here for easy maintenance.</p><pre>class ApiConstants {<br>  static const String baseUrl = &#39;https://dummyjson.com&#39;;<br>  static const String users = &#39;/users&#39;;<br>  static const String login = &#39;/auth/login&#39;;<br>  static const Duration connectTimeout = Duration(seconds: 10);<br>  static const Duration receiveTimeout = Duration(seconds: 10);<br>}</pre><p>✅ <strong>Explanation:</strong><br> Defines base URL, endpoints, and timeout durations — all used by our API client later.</p><p>🎨 core/theme/app_theme.dart</p><p>Next, let’s set up our light theme to define consistent colors and widget styles throughout the app. We’ll keep all our API endpoints and configurations centralized here for easy maintenance.</p><pre>class AppTheme {<br>  static ThemeData lightTheme = ThemeData(<br>    primarySwatch: Colors.blue,<br>    primaryColor: Colors.blue,<br>    scaffoldBackgroundColor: Colors.grey[50],<br>    appBarTheme: const AppBarTheme(<br>      backgroundColor: Colors.blue,<br>      foregroundColor: Colors.white,<br>      elevation: 0,<br>    ),<br>    cardTheme: CardTheme(<br>      elevation: 2,<br>      shape: RoundedRectangleBorder(<br>        borderRadius: BorderRadius.circular(12),<br>      ),<br>    ),<br>    elevatedButtonTheme: ElevatedButtonThemeData(<br>      style: ElevatedButton.styleFrom(<br>        backgroundColor: Colors.blue,<br>        foregroundColor: Colors.white,<br>        shape: RoundedRectangleBorder(<br>          borderRadius: BorderRadius.circular(8),<br>        ),<br>      ),<br>    ),<br>  );<br>}</pre><p>✅ <strong>Explanation:</strong><br> We’re using a <strong>light blue color palette</strong> with rounded components and modern card/button styling to give the app a consistent look.</p><h3>🌐 Step 3: API Integration Setup</h3><p>Now that the foundation is ready, we’ll move on to integrating our API using Dio and GetX.<br> We’ll start by configuring our API client and provider, then later connect everything to the GetX controller and UI.</p><h3>⚙️ Step 4: Setting Up Common API Call Structure</h3><p>Now that we have our <strong>core setup</strong> in place, let’s move on to configuring the <strong>network layer</strong> — the part of our app responsible for communicating with APIs.</p><p>We’ll create a <strong>clean, reusable structure</strong> for making API calls, handling errors, and processing responses.<br> This structure ensures that your app can easily scale as you add more API endpoints later.</p><p>Our setup includes four files:</p><pre>data/<br>├── models/<br>│   └── responses/<br>│       ├── api_response.dart<br>│       └── error_response.dart<br>│<br>└── providers/<br>    ├── api_provider.dart<br>    └── dio_client.dart</pre><h3>🧱 5. Base Response Models</h3><p>Before making any API call, it’s essential to define how responses are structured.<br> Let’s create two reusable models that represent <strong>successful</strong> and <strong>error</strong> responses.</p><p>📄 data/models/responses/api_response.dart</p><pre>class ApiResponse&lt;T&gt; {<br>  final T? data;<br>  final ErrorResponse? error;<br><br>  ApiResponse({this.data, this.error});<br><br>  bool get hasData =&gt; data != null;<br>  bool get hasError =&gt; error != null;<br>}</pre><p>✅ <strong>Explanation:</strong><br> This class wraps your API data and optionally includes an error object.<br> It helps manage both <strong>success</strong> and <strong>failure</strong> scenarios uniformly.</p><p>📄 data/models/responses/error_response.dart</p><pre>class ErrorResponse {<br>  final int? statusCode;<br>  final String message;<br><br>  ErrorResponse({this.statusCode, required this.message});<br>}</pre><p>✅ <strong>Explanation:</strong><br> This simple model defines a standardized structure for error responses — containing a status code and a message.</p><h3>🌐 6. API Client Configuration</h3><p>Now that we have our response structure ready, let’s set up <strong>Dio</strong>, the HTTP client we’ll use for API calls.</p><p>⚙️ data/providers/dio_client.dart</p><pre>class DioClient {<br>  late final Dio _dio;<br><br>  DioClient() {<br>    _dio = Dio(<br>      BaseOptions(<br>        baseUrl: ApiConstants.baseUrl,<br>        connectTimeout: Duration(milliseconds: ApiConstants.connectTimeout.inMilliseconds),<br>        receiveTimeout: Duration(milliseconds: ApiConstants.receiveTimeout.inMilliseconds),<br>        headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},<br>      ),<br>    );<br><br>    _dio.interceptors.add(LogInterceptor(responseBody: true, requestBody: true));<br>  }<br><br>  Dio get dio =&gt; _dio;<br>}</pre><p>✅ <strong>Explanation:</strong></p><ul><li>We use ApiConstants for base URL and timeout configuration.</li><li>Added a LogInterceptor to log every request and response, making debugging much easier.</li><li>The dio getter provides access to our configured instance from other layers.</li></ul><p><strong>🔌 API Provider Class</strong></p><p>This is where we define <strong>generic GET and POST</strong> methods that can be reused across all API calls in the app.</p><p>📄 data/providers/api_provider.dart</p><pre>class ApiProvider {<br>  final DioClient _dioClient;<br><br>  ApiProvider(this._dioClient);<br><br>  Future&lt;Either&lt;ErrorResponse, ApiResponse&gt;&gt; get(String endpoint) async {<br>    try {<br>      final response = await _dioClient.dio.get(endpoint);<br>      return Right(ApiResponse(data: response.data));<br>    } on DioException catch (e) {<br>      return Left(<br>        ErrorResponse(<br>          statusCode: e.response?.statusCode,<br>          message: e.message ?? &#39;Unknown error&#39;,<br>        ),<br>      );<br>    }<br>  }<br><br>  Future&lt;Either&lt;ErrorResponse, ApiResponse&gt;&gt; post(String endpoint, dynamic data) async {<br>    try {<br>      final response = await _dioClient.dio.post(endpoint, data: data);<br>      return Right(ApiResponse(data: response.data));<br>    } on DioException catch (e) {<br>      return Left(<br>        ErrorResponse(<br>          statusCode: e.response?.statusCode,<br>          message: e.message ?? &#39;Unknown error&#39;,<br>        ),<br>      );<br>    }<br>  }<br>}</pre><p>✅ <strong>Explanation:</strong></p><ul><li>The provider accepts a DioClient instance and exposes two methods — get() and post().</li><li>Both methods return an Either&lt;ErrorResponse, ApiResponse&gt;, powered by the <strong>Dartz</strong> package.</li><li>✅ Right → Successful response</li><li>❌ Left → Error response</li><li>This structure makes API handling cleaner and enforces a <strong>functional programming</strong> approach to error management.</li></ul><h4>🎯 Summary of This Step</h4><p>At this point, we’ve created a <strong>solid networking foundation</strong> that can handle:</p><ul><li>Consistent API responses</li><li>Clean error management</li><li>Centralized HTTP client setup</li></ul><p>This ensures your future API calls remain easy to maintain and scale — no repetitive boilerplate code needed.</p><h3>🌐 Step 7: Integrating the API and Building the User Model</h3><p>Now that we have our <strong>API setup ready</strong> using DioClient and ApiProvider, it’s time to integrate a <strong>real API</strong> to fetch user data and display it in the app.</p><p>For this tutorial, we’ll use a simple public API endpoint from <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a>:</p><p>👉 <strong>GET Request</strong></p><pre>https://jsonplaceholder.typicode.com/users</pre><p>This API returns a list of users with their name, username, email, address, phone, website, and company details.</p><p>A sample response looks like this:</p><pre>[<br>  {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Leanne Graham&quot;,<br>    &quot;username&quot;: &quot;Bret&quot;,<br>    &quot;email&quot;: &quot;Sincere@april.biz&quot;,<br>    &quot;address&quot;: {<br>      &quot;street&quot;: &quot;Kulas Light&quot;,<br>      &quot;suite&quot;: &quot;Apt. 556&quot;,<br>      &quot;city&quot;: &quot;Gwenborough&quot;,<br>      &quot;zipcode&quot;: &quot;92998-3874&quot;,<br>      &quot;geo&quot;: {<br>        &quot;lat&quot;: &quot;-37.3159&quot;,<br>        &quot;lng&quot;: &quot;81.1496&quot;<br>      }<br>    },<br>    &quot;phone&quot;: &quot;1-770-736-8031 x56442&quot;,<br>    &quot;website&quot;: &quot;hildegard.org&quot;,<br>    &quot;company&quot;: {<br>      &quot;name&quot;: &quot;Romaguera-Crona&quot;,<br>      &quot;catchPhrase&quot;: &quot;Multi-layered client-server neural-net&quot;,<br>      &quot;bs&quot;: &quot;harness real-time e-markets&quot;<br>    }<br>  }<br>]</pre><h4>🧩 Step 7.1: Create the User Model</h4><p>Let’s start by creating our data model to parse this response.</p><p>📁 <strong>File:</strong> lib/app/data/models/user_model.dart</p><p>We’ll use the json_serializable package to easily convert JSON data to Dart objects.</p><pre>part &#39;user_model.g.dart&#39;;<br><br>@JsonSerializable()<br>class User {<br>  final int id;<br>  final String name;<br>  final String username;<br>  final String email;<br>  final String phone;<br>  final String website;<br>  final Address address;<br>  final Company company;<br><br>  User({<br>    required this.id,<br>    required this.name,<br>    required this.username,<br>    required this.email,<br>    required this.phone,<br>    required this.website,<br>    required this.address,<br>    required this.company,<br>  });<br><br>  factory User.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$UserFromJson(json);<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$UserToJson(this);<br>}<br><br>@JsonSerializable()<br>class Address {<br>  final String street;<br>  final String suite;<br>  final String city;<br>  final String zipcode;<br>  final Geo geo;<br><br>  Address({<br>    required this.street,<br>    required this.suite,<br>    required this.city,<br>    required this.zipcode,<br>    required this.geo,<br>  });<br><br>  factory Address.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$AddressFromJson(json);<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$AddressToJson(this);<br>}<br><br>@JsonSerializable()<br>class Geo {<br>  final String lat;<br>  final String lng;<br><br>  Geo({required this.lat, required this.lng});<br><br>  factory Geo.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$GeoFromJson(json);<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$GeoToJson(this);<br>}<br><br>@JsonSerializable()<br>class Company {<br>  final String name;<br>  final String catchPhrase;<br>  final String bs;<br><br>  Company({<br>    required this.name,<br>    required this.catchPhrase,<br>    required this.bs,<br>  });<br><br>  factory Company.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$CompanyFromJson(json);<br>  Map&lt;String, dynamic&gt; toJson() =&gt; _$CompanyToJson(this);<br>}</pre><p>💡 <strong>Tip:</strong><br> Once your model is ready, run the following command to generate the .g.dart file automatically:</p><pre>flutter pub run build_runner build</pre><h4>🏗️ Step 7.2: Create the Repository Layer</h4><p>Now that we have the model, let’s create a <strong>repository class</strong> to call our API and return the parsed list of users.<br> This keeps the data fetching logic <strong>separate from controllers</strong> — a clean architecture principle that helps maintain scalability.</p><p>📁 <strong>File:</strong> lib/app/data/repositories/user_repository.dart</p><pre>import &#39;package:dartz/dartz.dart&#39;;<br>import &#39;package:flutter_getx_api_call/app/core/constants/api_constants.dart&#39;;<br>import &#39;package:flutter_getx_api_call/app/data/models/response/error_response.dart&#39;;<br>import &#39;package:flutter_getx_api_call/app/data/models/user_model.dart&#39;;<br>import &#39;package:flutter_getx_api_call/app/data/providers/api_provider.dart&#39;;<br><br>class UserRepository {<br>  final ApiProvider _apiProvider;<br><br>  UserRepository(this._apiProvider);<br><br>  Future&lt;Either&lt;ErrorResponse, List&lt;User&gt;&gt;&gt; getUsers() async {<br>    final response = await _apiProvider.get(<br>      &quot;https://jsonplaceholder.typicode.com${ApiConstants.users}&quot;,<br>    );<br><br>    return response.fold(<br>      (error) =&gt; Left(error),<br>      (apiResponse) {<br>        final users = (apiResponse.data as List)<br>            .map((user) =&gt; User.fromJson(user))<br>            .toList();<br>        return Right(users);<br>      },<br>    );<br>  }<br>}</pre><p>Here’s what’s happening:</p><ul><li>The repository calls our ApiProvider’s get() method.</li><li>It handles both success (Right) and error (Left) cases using the Either type from the <strong>Dartz</strong> package.</li><li>On success, the raw JSON list is parsed into a list of User objects.</li></ul><p>✅ <strong>That’s it for this part!</strong><br> We’ve now successfully set up the model and the repository to fetch and parse user data.</p><p>In the next part, we’ll connect everything together using:</p><ul><li>A <strong>GetX controller</strong> for state management</li><li>A <strong>Flutter view</strong> to display the user list</li><li>And a <strong>binding class</strong> for dependency injection</li></ul><p>Stay tuned — that’s where the magic happens! ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4884327b8dfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building a Login API Integration with MVI Pattern in Android Jetpack Compose]]></title>
            <link>https://medium.com/@asifulhaque1144/building-a-login-api-integration-with-mvi-pattern-in-android-jetpack-compose-b346b396f497?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/b346b396f497</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[mvi-architecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 17:52:13 GMT</pubDate>
            <atom:updated>2025-09-04T18:04:39.687Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-iii-af11a2ad223f"><em>previous blog</em></a> I walked through integrating a <strong>GET API</strong> (users list) using the <strong>MVI architecture pattern</strong> with Jetpack Compose. Now, let’s take the next step and implement a <strong>POST API</strong> example by building a <strong>Login feature</strong>.</p><p>Unlike GET requests, <strong>POST requests</strong> often involve:</p><ul><li>Sending a <strong>request body</strong> (e.g., username &amp; password).</li><li>Handling <strong>API response</strong> with success or failure.</li><li>Managing <strong>loading &amp; error states</strong> while submitting data.</li></ul><p>To keep things clean and scalable, we’ll continue with the same <strong>MVI (Model-View-Intent) architecture pattern</strong>. This ensures that:</p><ul><li>Our <strong>core layer</strong> remains reusable across the project.</li><li>The <strong>data, domain, and presentation layers</strong> handle responsibilities separately.</li><li>Adding new features (like registration, profile, etc.) later becomes seamless.</li></ul><h3>📂 Project Folder Structure</h3><p>The project is divided into clear modules following <strong>clean architecture + MVI</strong> principles.</p><h3>🔹 Core Layer (common for the entire app)</h3><p>These files are generic utilities and remain unchanged for all features.</p><pre>core/<br> ├── common_components/<br> │    └── Error_items.kt<br> ├── config/<br> │    └── BuildConfigFields.kt<br> ├── constants/<br> │    └── ApiConstants.kt<br> ├── ui/<br> │    └── DataState.kt</pre><h3>🔹 Data Layer (API &amp; Repository Implementation)</h3><p>Responsible for <strong>network requests</strong>, <strong>DTOs</strong>, and mapping responses to domain models.</p><pre>data/<br> ├── mapper/<br> │    └── LoginMapper.kt<br> ├── remote/<br> │    ├── api/<br> │    │    └── AuthApiServices.kt<br> │    ├── dto/<br> │    │    ├── LoginRequest.kt<br> │    │    └── LoginResponse.kt<br> ├── repository/<br> │    └── AuthRepositoryImpl.kt</pre><h3>🔹 Domain Layer (Business Logic &amp; Use Cases)</h3><p>Contains <strong>models</strong>, <strong>abstract repository interfaces</strong>, and <strong>use cases</strong>.</p><pre>domain/<br> ├── model/<br> │    └── Login.kt<br> ├── repository/<br> │    └── auth/<br> │         └── AuthRepository.kt<br> ├── usecase/<br> │    └── auth/<br> │         └── LoginUseCase.kt</pre><h3>🔹 Presentation Layer (UI + ViewModel + State Handling)</h3><p>Handles <strong>UI rendering</strong>, <strong>user events</strong>, and <strong>state management</strong> with MVI.</p><pre>presentation/<br> ├── ui/<br> │    └── auth/<br> │         └── LoginScreen.kt<br> ├── viewmodel/<br> │    └── auth/<br> │         └── LoginViewModel.kt<br> │    └── events/<br> │         └── LoginEvent.kt<br> │    └── states/<br> │         └── LoginState.kt</pre><h3>🔹 Dependency Injection (DI Layer)</h3><p>Provides dependencies for API services and repositories.</p><pre>di/<br> └── AuthNetworkModule.kt</pre><h3>🔹 Root Project Files</h3><p>Finally, the entry points of our app:</p><pre>AppNavigation.kt     // Handles navigation flows<br>MainActivity.kt      // Host activity for Jetpack Compose<br>MainApp.kt           // Annotated with @HiltAndroidApp</pre><p>So, now, let’s go into the coding part of our project.</p><h3>📂Data Layer</h3><h3>🔹 DTOs (Request &amp; Response)</h3><p>We’ll start by defining our request and response classes.</p><pre>// data/remote/dto/LoginRequest.kt<br>data class LoginRequest(<br>    val username: String,<br>    val password: String<br>)</pre><pre>// data/remote/dto/LoginResponse.kt<br>data class LoginResponse(<br>    val accessToken: String,<br>    val refreshToken: String,<br>    val id: Int,<br>    val username: String,<br>    val email: String,<br>    val firstName: String,<br>    val lastName: String,<br>    val gender: String,<br>    val image: String<br>)</pre><h3>🔹 API Service</h3><p>Next, define the login API endpoint.</p><pre>// data/remote/api/AuthApiServices.kt<br>interface AuthApiServices {<br>    @POST(&quot;auth/login&quot;)<br>    suspend fun login(@Body loginRequest: LoginRequest): LoginResponse<br>}</pre><h3>🔹 Repository Implementation</h3><p>The repository makes the API call and maps it to our <strong>domain model</strong>. (The Repository interface is in domain layer)</p><pre>// data/repository/AuthRepositoryImpl.kt<br>class AuthRepositoryImpl @Inject constructor(<br>    private val authApiServices: AuthApiServices<br>) : AuthRepository {<br>    override suspend fun login(loginRequest: LoginRequest): Result&lt;Login&gt; {<br>        return try {<br>            val response = authApiServices.login(loginRequest)<br>            Result.success(response.toDomain())<br>        } catch (e: Exception) {<br>            Result.failure(e)<br>        }<br>    }<br>}</pre><h3>🏗 Domain Layer</h3><h4>🔹 Domain Model</h4><p>We create a clean Login model for the domain layer.</p><pre>// domain/model/Login.kt<br>data class Login(<br>    val accessToken: String,<br>    val refreshToken: String,<br>    val id: Int,<br>    val username: String,<br>    val email: String,<br>    val firstName: String,<br>    val lastName: String,<br>    val gender: String,<br>    val image: String<br>)</pre><h3>🔹 Repository Interface</h3><p>The repository interface ensures the <strong>presentation layer</strong> only depends on abstractions.</p><pre>// domain/repository/auth/AuthRepository.kt<br>interface AuthRepository {<br>    suspend fun login(loginRequest: LoginRequest): Result&lt;Login&gt;<br>}</pre><p>And here’s the <strong>use case interface </strong>which adds another layer of abstraction to handle the business logic, make our code more loosely coupled, ensures re-usability and creates one separation of concern so that we can test our business logics properly without depending one any other layer:</p><pre>class LoginUseCase @Inject constructor(private val authRepository: AuthRepository) {<br>    suspend operator fun invoke(loginRequest: LoginRequest): Result&lt;Login&gt; {<br>        return authRepository.login(loginRequest)<br>    }<br>}</pre><h3>🎛 Presentation Layer</h3><h3>🔹 State Class</h3><p>Represents the <strong>UI state</strong> of the login screen.</p><pre>// presentation/viewmodel/states/LoginState.kt<br>data class LoginState(<br>    val isLoading: Boolean = false,<br>    val login: Login? = null,<br>    val error: String? = null<br>)</pre><h3>🔹 Event Class</h3><p>Defines <strong>user actions</strong> such as triggering login.</p><pre>// presentation/viewmodel/events/LoginEvent.kt<br>sealed class LoginEvent {<br>    data class Login(val loginRequest: LoginRequest) : LoginEvent()<br>}</pre><h3>🔹 ViewModel</h3><p>The ViewModel handles login logic, updates state, and emits <strong>navigation events</strong>.</p><pre>// presentation/viewmodel/auth/LoginViewModel.kt<br>@HiltViewModel<br>class LoginViewModel @Inject constructor(<br>    private val loginUseCase: LoginUseCase<br>) : ViewModel() {<br>    private val _state = MutableStateFlow(LoginState())<br>    val state: StateFlow&lt;LoginState&gt; = _state.asStateFlow()<br><br>    private val _navigationEvent = Channel&lt;LoginNavigationEvent&gt;(Channel.BUFFERED)<br>    val navigationEvent = _navigationEvent.receiveAsFlow()<br><br>    fun onAction(event: LoginEvent) {<br>        when (event) {<br>            is LoginEvent.Login -&gt; login(event.loginRequest)<br>        }<br>    }<br><br>    private fun login(loginRequest: LoginRequest) {<br>        viewModelScope.launch {<br>            _state.value = _state.value.copy(isLoading = true)<br>            val result = loginUseCase(loginRequest)<br>            result.onSuccess { loginData -&gt;<br>                _state.value = _state.value.copy(login = loginData, isLoading = false)<br>                _navigationEvent.trySend(LoginNavigationEvent.NavigateToUser)<br>            }.onFailure {<br>                _state.value = _state.value.copy(error = it.message, isLoading = false)<br>            }<br>        }<br>    }<br><br>    fun clearError() {<br>        _state.value = _state.value.copy(error = null)<br>    }<br>}<br><br>sealed class LoginNavigationEvent {<br>    object NavigateToUser : LoginNavigationEvent()<br>}</pre><h3>🔹 UI (Composable Screen)</h3><p>Our LoginScreen handles inputs, shows loading state, errors, and triggers the event.</p><pre>@Composable<br>fun LoginScreenRoute(<br>    navController: NavController,<br>    modifier: Modifier = Modifier,<br>    viewModel: LoginViewModel = hiltViewModel(),<br>) {<br>    val context = LocalContext.current<br>    val state by viewModel.state.collectAsState()<br><br>    // Observe navigation events<br>    LaunchedEffect(Unit) {<br>        viewModel.navigationEvent.collect { event -&gt;<br>            when (event) {<br>                is LoginNavigationEvent.NavigateToUser -&gt; navController.navigate(&quot;user&quot;)<br>            }<br>        }<br>    }<br><br>    // Show error as toast<br>    LaunchedEffect(state.error) {<br>        state.error?.let {<br>            context.showShortToast(it)<br>            viewModel.clearError()<br>        }<br>    }<br><br>    LoginScreen(<br>        modifier = modifier,<br>        state = state,<br>        onAction = viewModel::onAction,<br>    )<br>}</pre><p>And the full <strong>Login form</strong> includes fields for username, password, and a login button — with proper loading indicators and error handling.</p><h3>🔌 Dependency Injection</h3><p>We register our AuthApiServices with Hilt.</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object AuthNetworkModule {<br><br>    @Provides<br>    @Singleton<br>    @AuthRetrofit<br>    fun provideAuthOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient =<br>        OkHttpClient.Builder().addInterceptor(loggingInterceptor).build()<br><br>    @Provides<br>    @Singleton<br>    @AuthRetrofit<br>    fun provideAuthRetrofit(@AuthRetrofit okHttpClient: OkHttpClient): Retrofit =<br>        Retrofit.Builder()<br>            .baseUrl(BuildConfigFields.BASE_URL)<br>            .client(okHttpClient)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br><br>    @Provides<br>    @Singleton<br>    fun provideAuthApi(@AuthRetrofit retrofit: Retrofit): AuthApiServices =<br>        retrofit.create(AuthApiServices::class.java)<br>}<br><br>@Qualifier<br>@Retention(AnnotationRetention.BINARY)<br>annotation class AuthRetrofit</pre><h3>🧭 Navigation &amp; Main Setup</h3><p>Finally, let’s set up navigation and hook our login screen into the app.</p><pre>@Composable<br>fun AppNavigation() {<br>    val navController = rememberNavController()<br>    NavHost(navController = navController, startDestination = &quot;login&quot;) {<br>        composable(&quot;login&quot;) { LoginScreenRoute(navController) }<br>        composable(&quot;home&quot;) { HomeScreen() }<br>        composable(&quot;user&quot;) { UserScreenRoute() }<br>    }<br>}</pre><p>And in MainActivity:</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MaterialTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    AppNavigation()<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>🎯 Final Thoughts</h3><p>We’ve now implemented a <strong>Login API integration (POST request)</strong> using <strong>Jetpack Compose + MVI architecture</strong>.</p><p>Key takeaways:</p><ul><li><strong>MVI keeps state predictable</strong> and ensures UI is reactive.</li><li><strong>Domain layer</strong> isolates business logic.</li><li><strong>Repository pattern</strong> decouples data sources from UI.</li><li><strong>StateFlow + Channels</strong> handle both continuous state and one-time navigation events.</li></ul><p>This structure can easily be extended for <strong>signup, logout, or profile APIs</strong> while keeping the app clean and scalable.</p><p><strong><em>My project’s github link:</em></strong></p><blockquote><a href="https://github.com/Asif047/AndroidJetpackComposeMVIExample">https://github.com/Asif047/AndroidJetpackComposeMVIExample</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b346b396f497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose + MVI: A Complete Guide with Movie API Integration (Part-III)]]></title>
            <link>https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-iii-af11a2ad223f?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/af11a2ad223f</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[mvi-architecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 16:17:39 GMT</pubDate>
            <atom:updated>2025-09-04T17:53:53.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oDgWHG4CqdxScIpuz35vgw.png" /></figure><p>In the previous part, we have set-up our Data layer, learned about saving data in room DB &amp; using them as Single Source of Truth and how to set up pagination on scroll.</p><p><strong>Previous part link:</strong></p><p><a href="https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-ii-b018ac6284ce">Jetpack Compose + MVI: A Complete Guide with Movie API Integration (Part-II)</a></p><p>In this part, we will learn about how to set-up the <strong>Domain </strong>layer and <strong>Presentation </strong>layer and add the <strong>Dependency Injection (DI)</strong> modules.</p><h3>domain</h3><p>Represents the business logic layer:</p><ul><li>model: Domain-level models used across the app</li><li>repository: Repository interface (to be used by use cases)</li><li>usecase: Business use cases like GetMoviesUseCase</li></ul><h3>presentation</h3><p>This layer handles all UI and state management:</p><ul><li>ui: Composables like MovieScreen.kt</li><li>viewmodel:</li></ul><p>- events: User actions/events (MovieEvent)</p><p>- states: View state representation (MovieState)</p><p>- MovieViewModel: Business logic holder following MVI</p><h3>di</h3><p>that’s the Hilt dependency injection setup:</p><ul><li>NetworkModule: Provides Retrofit &amp; API dependencies</li><li>DatabaseModule: Provides Room dependencies</li><li>RepositoryModule: Provides repository instances</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>At first, in the domain layer, inside repository package, we should write the repository interface:</p><blockquote>// domain/repository/MovieRepository.kt</blockquote><pre>interface MovieRepository {<br>    fun getPopularMoviesPaged(): Flow&lt;PagingData&lt;Movie&gt;&gt;<br>    fun getAllMovies(): Flow&lt;List&lt;Movie&gt;&gt;<br>}</pre><p>Write it’s implementation in the Data layer.</p><blockquote>// data/repository/MovieRepositoryImpl.kt</blockquote><pre>@OptIn(ExperimentalPagingApi::class)<br>@Singleton<br>class MovieRepositoryImpl @Inject constructor(<br>    private val movieApi: MovieApi,<br>    private val movieDatabase: MovieDatabase<br>) : MovieRepository {<br><br>    override fun getPopularMoviesPaged(): Flow&lt;PagingData&lt;Movie&gt;&gt; {<br>        return Pager(<br>            config = PagingConfig(<br>                pageSize = 20,<br>                enablePlaceholders = false,<br>                prefetchDistance = 3<br>            ),<br>            remoteMediator = MovieRemoteMediator(<br>                movieApi = movieApi,<br>                movieDatabase = movieDatabase<br>            ),<br>            pagingSourceFactory = {<br>                movieDatabase.movieDao().getAllMoviesPaging()<br>            }<br>        ).flow.map { pagingData -&gt;<br>            pagingData.map { entity -&gt; entity.toDomain() }<br>        }<br>    }<br><br>    override fun getAllMovies(): Flow&lt;List&lt;Movie&gt;&gt; {<br>        return movieDatabase.movieDao().getAllMovies()<br>            .map { entities -&gt; entities.map { entity -&gt; entity.toDomain() } }<br>    }<br>}</pre><p>Now, write the usecases inside the domain layer.</p><blockquote>// domain/usecase/GetPopularMoviesUseCase.kt</blockquote><pre>@Singleton<br>class GetPopularMoviesUseCase @Inject constructor(<br>    private val repository: MovieRepository<br>) {<br>    operator fun invoke(): Flow&lt;PagingData&lt;Movie&gt;&gt; {<br>        return repository.getPopularMoviesPaged()<br>    }<br>}</pre><p>Now, it’s time to prepare our presentation layer which will contain Events, States, Viewmodel and the UI Compose.</p><p>Here’s the Event class:</p><blockquote>// presentation/viewmodel/events/MovieEvent.kt</blockquote><pre>sealed class MovieEvent {<br>    data object LoadMovies : MovieEvent()<br>    data object Refresh : MovieEvent()<br>    data class OnMovieClick(val movie: Movie) : MovieEvent()<br>}</pre><p>🧠 Why Use a sealed class?</p><p>A sealed class is ideal for representing a <strong>fixed set of known types</strong>, which makes it perfect for modeling events in MVI.</p><h4>✅ Benefits:</h4><ol><li><strong>Exhaustiveness in </strong><strong>when statements</strong></li></ol><ul><li>The compiler ensures all event types are handled, reducing bugs.</li></ul><p><strong>2. Strong typing</strong></p><ul><li>Each event can carry data (like OnMovieClick(movie)), which makes the architecture more scalable and expressive.</li></ul><p><strong>3. Encapsulation of intent</strong></p><ul><li>Clearly separates user-driven events from system state or logic.</li></ul><p>And here’s the state class:</p><blockquote>// presentation/viewmodel/states/MovieState.kt</blockquote><pre>data class MovieState(<br>    val isLoading: Boolean = false,<br>    val isRefreshing: Boolean = false,<br>    val error: String? = null<br>)</pre><p>And here’s our viewmodel which will hold all states and it’s update:</p><blockquote>// presentation/viewmodel/MovieViewModel.kt</blockquote><pre>@HiltViewModel<br>class MovieViewModel @Inject constructor(<br>    private val getPopularMoviesUseCase: GetPopularMoviesUseCase<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(MovieState())<br>    val state: StateFlow&lt;MovieState&gt; = _state.asStateFlow()<br><br>    val moviesPagingDataFlow: Flow&lt;PagingData&lt;Movie&gt;&gt; =<br>        getPopularMoviesUseCase()<br>            .cachedIn(viewModelScope)<br><br>    fun onAction(action: MovieEvent) {<br>        when (action) {<br>            is MovieEvent.LoadMovies -&gt; {<br>                // Movies are automatically loaded through paging<br>            }<br><br>            is MovieEvent.Refresh -&gt; {<br><br>            }<br><br>            is MovieEvent.OnMovieClick -&gt; {<br>                // Handle movie click navigation<br>            }<br>        }<br>    }<br><br>    private fun updateState(update: (MovieState) -&gt; MovieState) {<br>        _state.value = update(_state.value)<br>    }<br>}</pre><p>So, now we can create our UI compose to show the movie list in our screen using Viewmodel, Event and States</p><p>Here’s our Compose UI screen:</p><blockquote>// presentation/ui/MovieScreen.kt</blockquote><pre>@Composable<br>fun MoviesScreen(<br>    viewModel: MovieViewModel = hiltViewModel()<br>) {<br>    val moviesPagingItems = viewModel.moviesPagingDataFlow.collectAsLazyPagingItems()<br><br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>    ) {<br>        LazyColumn(<br>            modifier = Modifier.fillMaxSize(),<br>            contentPadding = PaddingValues(16.dp),<br>            verticalArrangement = Arrangement.spacedBy(16.dp)<br>        ) {<br>            items(<br>                count = moviesPagingItems.itemCount,<br>                key = moviesPagingItems.itemKey { it.id }<br>            ) { index -&gt;<br>                val movie = moviesPagingItems[index]<br>                if (movie != null) {<br>                    MovieItem(<br>                        movie = movie,<br>                        onClick = { viewModel.onAction(MovieEvent.OnMovieClick(movie)) }<br>                    )<br>                }<br>            }<br><br>            // Handle loading states<br>            moviesPagingItems.apply {<br>                when {<br>                    loadState.refresh is LoadState.Loading -&gt; {<br>                        item {<br>                            Box(<br>                                modifier = Modifier<br>                                    .fillMaxWidth()<br>                                    .padding(16.dp),<br>                                contentAlignment = Alignment.Center<br>                            ) {<br>                                CircularProgressIndicator()<br>                            }<br>                        }<br>                    }<br><br>                    loadState.refresh is LoadState.Error -&gt; {<br>                        val error = loadState.refresh as LoadState.Error<br>                        item {<br>                            ErrorItem(<br>                                message = error.error.localizedMessage ?: &quot;Unknown error&quot;,<br>                                // Call retry() directly on moviesPagingItems<br>                                onRetry = { moviesPagingItems.retry() }<br>                            )<br>                        }<br>                    }<br><br>                    loadState.append is LoadState.Loading -&gt; {<br>                        item {<br>                            Box(<br>                                modifier = Modifier<br>                                    .fillMaxWidth()<br>                                    .padding(16.dp),<br>                                contentAlignment = Alignment.Center<br>                            ) {<br>                                CircularProgressIndicator(<br>                                    modifier = Modifier.size(24.dp)<br>                                )<br>                            }<br>                        }<br>                    }<br><br>                    loadState.append is LoadState.Error -&gt; {<br>                        val error = loadState.append as LoadState.Error<br>                        item {<br>                            ErrorItem(<br>                                message = error.error.localizedMessage ?: &quot;Unknown error&quot;,<br>                                onRetry = { moviesPagingItems.retry() }<br>                            )<br>                        }<br>                    }<br>                }<br>            }<br>        }<br><br>        val uiState by viewModel.state.collectAsState()<br>        if (uiState.isLoading) {<br>            Box(<br>                modifier = Modifier.fillMaxSize()<br>            ) {<br>                CircularProgressIndicator()<br>            }<br>        }<br>        uiState.error?.let { errorMessage -&gt;<br>            // Display a global error message if needed<br>        }<br>    }<br>}<br><br>@Composable<br>fun MovieItem(<br>    movie: Movie,<br>    onClick: () -&gt; Unit<br>) {<br>    Card(<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .clickable { onClick() },<br>        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)<br>    ) {<br>        Row(<br>            modifier = Modifier.padding(16.dp)<br>        ) {<br><br><br>            Spacer(modifier = Modifier.width(16.dp))<br><br>            Column(<br>                modifier = Modifier.weight(1f)<br>            ) {<br>                Text(<br>                    text = movie.title,<br>                    style = MaterialTheme.typography.titleMedium,<br>                    fontWeight = FontWeight.Bold,<br>                    maxLines = 2,<br>                    overflow = TextOverflow.Ellipsis<br>                )<br><br>                Spacer(modifier = Modifier.height(4.dp))<br><br>                Text(<br>                    text = movie.releaseDate,<br>                    style = MaterialTheme.typography.bodySmall,<br>                    color = MaterialTheme.colorScheme.onSurfaceVariant<br>                )<br><br>                Spacer(modifier = Modifier.height(8.dp))<br><br>                Text(<br>                    text = movie.overview,<br>                    style = MaterialTheme.typography.bodyMedium,<br>                    maxLines = 3,<br>                    overflow = TextOverflow.Ellipsis<br>                )<br><br>                Spacer(modifier = Modifier.height(8.dp))<br><br>                Row(<br>                    verticalAlignment = Alignment.CenterVertically<br>                ) {<br>                    Icon(<br>                        imageVector = Icons.Default.Star,<br>                        contentDescription = &quot;Rating&quot;,<br>                        tint = Color.Yellow,<br>                        modifier = Modifier.size(16.dp)<br>                    )<br><br>                    Spacer(modifier = Modifier.width(4.dp))<br><br>                    Text(<br>                        text = &quot;${movie.voteAverage}/10&quot;,<br>                        style = MaterialTheme.typography.bodySmall<br>                    )<br><br>                    Spacer(modifier = Modifier.width(16.dp))<br><br>                    Text(<br>                        text = &quot;(${movie.voteCount} votes)&quot;,<br>                        style = MaterialTheme.typography.bodySmall,<br>                        color = MaterialTheme.colorScheme.onSurfaceVariant<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>In the screen, we have used one common UI component named ErrorItem, which we will write in the core package.</p><blockquote>// core/common_components/ErrorItem.kt</blockquote><pre>@Composable<br>fun ErrorItem(<br>    message: String,<br>    onRetry: () -&gt; Unit<br>) {<br>    Column(<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .padding(16.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(<br>            text = message,<br>            style = MaterialTheme.typography.bodyMedium,<br>            textAlign = TextAlign.Center,<br>            color = MaterialTheme.colorScheme.error<br>        )<br><br>        Spacer(modifier = Modifier.height(8.dp))<br><br>        Button(onClick = onRetry) {<br>            Text(&quot;Retry&quot;)<br>        }<br>    }<br>}</pre><p>So, now we can call MovieScreen UI in our MainActivity class:</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MaterialTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    MoviesScreen()<br>                }<br>            }<br>        }<br>    }<br>}<br><br></pre><p>Before building the project, we must declare Dependency Injection(di) classes.</p><p>In the di package, we will create three di classes- DatabaseModule, NetworkModule, RepositoryModule.</p><blockquote>// di/DatabaseModule.kt</blockquote><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object DatabaseModule {<br>    @Provides<br>    @Singleton<br>    fun provideMovieDatabase(@ApplicationContext context: Context): MovieDatabase {<br>        return Room.databaseBuilder(<br>            context,<br>            MovieDatabase::class.java,<br>            &quot;movie_database&quot;<br>        ).build()<br>    }<br>    @Provides<br>    fun provideMovieDao(database: MovieDatabase): MovieDao {<br>        return database.movieDao()<br>    }<br><br>    @Provides<br>    fun provideRemoteKeysDao(database: MovieDatabase): RemoteKeysDao {<br>        return database.remoteKeysDao()<br>    }<br>}</pre><blockquote>// di/NetworkModule.kt</blockquote><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object NetworkModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideApiKeyInterceptor(): Interceptor {<br>        return Interceptor { chain -&gt;<br>            val original = chain.request()<br>            val originalHttpUrl = original.url<br><br>            val url = originalHttpUrl.newBuilder()<br>                .addQueryParameter(&quot;api_key&quot;, BuildConfigFields.API_KEY)<br>                .build()<br><br>            val requestBuilder = original.newBuilder()<br>                ./service/https://medium.com/url(url)<br><br>            chain.proceed(requestBuilder.build())<br>        }<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideLoggingInterceptor(): HttpLoggingInterceptor {<br>        return HttpLoggingInterceptor().apply {<br>            level = if (BuildConfigFields.IS_DEBUG) {<br>                HttpLoggingInterceptor.Level.BODY<br>            } else {<br>                HttpLoggingInterceptor.Level.NONE<br>            }<br>        }<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideOkHttpClient(<br>        apiKeyInterceptor: Interceptor,<br>        loggingInterceptor: HttpLoggingInterceptor<br>    ): OkHttpClient {<br>        return OkHttpClient.Builder()<br>            .addInterceptor(apiKeyInterceptor)<br>            .addInterceptor(loggingInterceptor)<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {<br>        return Retrofit.Builder()<br>            .baseUrl(BuildConfigFields.BASE_URL)<br>            .client(okHttpClient)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideMovieApi(retrofit: Retrofit): MovieApi {<br>        return retrofit.create(MovieApi::class.java)<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideGson(): Gson {<br>        return Gson()<br>    }<br>}</pre><blockquote>// di/RepositoryModule.kt</blockquote><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>abstract class RepositoryModule {<br><br>    @Binds<br>    abstract fun bindMovieRepository(<br>        movieRepositoryImpl: MovieRepositoryImpl<br>    ): MovieRepository<br>}</pre><p>Now, create one <strong>Application </strong>class for the app and plays a critical role in enabling Hilt for dependency injection.</p><p>In the manifest use the application name inside the application tag:</p><blockquote>android:name=”MovieApp”</blockquote><p>Add the necessary permission in the manifest file:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><p>Ok that’s it, finally we can build and run our project.</p><p><strong><em>My project’s github link:</em></strong></p><blockquote><a href="https://github.com/Asif047/AndroidJetpackComposeMVIExample"><em>https://github.com/Asif047/AndroidJetpackComposeMVIExample</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af11a2ad223f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose + MVI: A Complete Guide with Movie API Integration (Part-II)]]></title>
            <link>https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-ii-b018ac6284ce?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/b018ac6284ce</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvi-architecture]]></category>
            <category><![CDATA[paging]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[room]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 16:27:27 GMT</pubDate>
            <atom:updated>2025-07-12T17:50:54.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oDgWHG4CqdxScIpuz35vgw.png" /></figure><p>In the previous part, we have discussed about the benefits of MVI architecture, project structure and how we should set-up our gradle files.</p><p><strong>Previous part link:</strong></p><p><a href="https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-i-f45624a8405a">Jetpack Compose + MVI: A Complete Guide with Movie API Integration (Part- I)</a></p><p>In this part, we will set-up the data layer of our project.</p><p>So, let me go through about the entire project package structure flow once more a better understanding.</p><p><strong>Project Structure:</strong></p><pre>app<br>├── core<br>│ ├── common_components<br>│ ├── config<br>│ ├── constants<br>│ └── ui<br>├── data<br>│ ├── local<br>│ │ ├── dao<br>│ │ ├── database<br>│ │ └── entities<br>│ ├── remote<br>│ │ ├── api<br>│ │ ├── dto<br>│ │ ├── mediator<br>│ │ └── repository<br>│ └── mappers<br>├── di<br>├── domain<br>│ ├── model<br>│ ├── repository<br>│ └── usecase<br>├── presentation<br>│ ├── ui<br>│ └── viewmodel<br>│ ├── events<br>│ └── states<br>├── MainActivity.kt<br>└── MovieApp.kt</pre><p>At first, we need to create some common files which will be used throughout the application.</p><p>So, first set-up the core files of project, in the core package:</p><blockquote>// core/config/BuildConfigFields.kt</blockquote><pre>object BuildConfigFields {<br>    val API_KEY: String get() = BuildConfig.TMDB_API_KEY<br>    val BASE_URL: String get() = BuildConfig.BASE_URL<br>    val IS_DEBUG: Boolean get() = BuildConfig.DEBUG<br>}</pre><p>This BuildConfigFields file is used to define the Urls and API keys which are called in gradle file to keep the project Urls &amp; API keys secured in generated files.</p><blockquote>// core/constants/AppConstants.kt</blockquote><pre>object ApiConstants {<br>    const val BASE_URL = &quot;https://api.themoviedb.org/3/&quot;<br><br>    // Endpoints<br>    const val POPULAR_MOVIES = &quot;movie/popular&quot;<br>    const val TOP_RATED_MOVIES = &quot;movie/top_rated&quot;<br>    const val MOVIE_DETAILS = &quot;movie/{movie_id}&quot;<br><br>    // Query Parameters<br>    const val QUERY_API_KEY = &quot;api_key&quot;<br>    const val QUERY_PAGE = &quot;page&quot;<br>    const val QUERY_LANGUAGE = &quot;language&quot;<br><br>    // Default Values<br>    const val DEFAULT_PAGE = 1<br>    const val DEFAULT_LANGUAGE = &quot;en-US&quot;<br><br>    const val IMAGE_BASE_URL = &quot;https://image.tmdb.org/t/p/w500&quot;<br>    const val IMAGE_BASE_URL_ORIGINAL = &quot;https://image.tmdb.org/t/p/original&quot;<br>}</pre><p>Now, come to data layer, where we will at first create the data to parse the json from API.</p><blockquote>// data/remote/dto/MoviesResponseDto.kt</blockquote><pre>data class MoviesResponseDto(<br>    @SerializedName(&quot;page&quot;) val page: Int,<br>    @SerializedName(&quot;results&quot;) val results: List&lt;MovieDto&gt;,<br>    @SerializedName(&quot;total_pages&quot;) val totalPages: Int,<br>    @SerializedName(&quot;total_results&quot;) val totalResults: Int<br>)</pre><blockquote>// data/remote/dto/MovieDto.kt</blockquote><pre>data class MovieDto(<br>    @SerializedName(&quot;adult&quot;) val adult: Boolean,<br>    @SerializedName(&quot;backdrop_path&quot;) val backdropPath: String?,<br>    @SerializedName(&quot;genre_ids&quot;) val genreIds: List&lt;Int&gt;,<br>    @SerializedName(&quot;id&quot;) val id: Int,<br>    @SerializedName(&quot;original_language&quot;) val originalLanguage: String,<br>    @SerializedName(&quot;original_title&quot;) val originalTitle: String,<br>    @SerializedName(&quot;overview&quot;) val overview: String,<br>    @SerializedName(&quot;popularity&quot;) val popularity: Double,<br>    @SerializedName(&quot;poster_path&quot;) val posterPath: String?,<br>    @SerializedName(&quot;release_date&quot;) val releaseDate: String,<br>    @SerializedName(&quot;title&quot;) val title: String,<br>    @SerializedName(&quot;video&quot;) val video: Boolean,<br>    @SerializedName(&quot;vote_average&quot;) val voteAverage: Double,<br>    @SerializedName(&quot;vote_count&quot;) val voteCount: Int<br>)</pre><p>These <strong>data transfer object (DTO) </strong>classes used to map the JSON response from the Movie API into a Kotlin object.</p><h3>🧠 Why @SerializedName is Required</h3><p>@SerializedName(&quot;...&quot;) is a Gson annotation used to <strong>map the exact JSON field name</strong> to a Kotlin property.</p><ul><li>In many cases, <strong>JSON field names use snake_case</strong> (backdrop_path) while Kotlin typically uses <strong>camelCase</strong> (backdropPath).</li><li>Without @SerializedName, Gson wouldn&#39;t know how to match JSON keys to your Kotlin properties during parsing.</li></ul><p><strong>N.B: We can use some better libraries like Moshi to avoid these kind of serializations and make it easier to parse json. Which we will learn later.</strong></p><p>Now, create the API calling interface with proper method annotation.</p><blockquote>// data/remote/api/MovieApi.kt</blockquote><pre>interface MovieApi {<br>    @GET(ApiConstants.POPULAR_MOVIES)<br>    suspend fun getPopularMovies(<br>        @Query(ApiConstants.QUERY_PAGE) page: Int = ApiConstants.DEFAULT_PAGE,<br>        @Query(ApiConstants.QUERY_LANGUAGE) language: String = ApiConstants.DEFAULT_LANGUAGE<br>    ): MoviesResponseDto<br>}</pre><p>Now, set-up the local caching using Room db. For that will need Database class, Entities and Dao for Room db operations.</p><blockquote>// data/local/database/MovieDatabase.kt</blockquote><pre>@Database(<br>    entities = [MovieEntity::class, RemoteKeys::class],<br>    version = 1,<br>    exportSchema = false<br>)<br>@TypeConverters(Converters::class)<br>abstract class MovieDatabase : RoomDatabase() {<br>    abstract fun movieDao(): MovieDao<br>    abstract fun remoteKeysDao(): RemoteKeysDao<br>}</pre><blockquote>// data/local/database/Converters.kt</blockquote><pre>class Converters {<br>    @TypeConverter<br>    fun fromStringList(value: List&lt;Int&gt;): String {<br>        return Gson().toJson(value)<br>    }<br><br>   @TypeConverter<br>    fun toStringList(value: String): List&lt;Int&gt; {<br>        return Gson().fromJson(value, object : TypeToken&lt;List&lt;Int&gt;&gt;() {}.type)<br>    }<br>}</pre><h3>🏗️ Why @TypeConverter and Converters Class Are Required</h3><p>Room Database only supports <strong>primitive types</strong> (Int, String, Boolean, etc.) and a few custom ones <strong>out of the box</strong>.<br> But sometimes, you need to store <strong>complex data types</strong> like List&lt;Int&gt;, List&lt;String&gt;, Date, or Map.</p><p>In this case:<br>val genreIds: List&lt;Int&gt;<br>This cannot be stored directly in a Room column.</p><h3>✅ Solution: TypeConverter</h3><p>Room allows you to define custom conversions using the @TypeConverter annotation.</p><p>Your Converters class does exactly that.</p><p>Now, create the entity classes where we will set the tables with its columns:</p><blockquote>// data/local/entities/MovieEntity.kt</blockquote><pre>@Entity(tableName = &quot;movies&quot;)<br>data class MovieEntity(<br>    @PrimaryKey val id: Int,<br>    val adult: Boolean,<br>    val backdropPath: String?,<br>    val genreIds: String, // JSON string of genre IDs<br>    val originalLanguage: String,<br>    val originalTitle: String,<br>    val overview: String,<br>    val popularity: Double,<br>    val posterPath: String?,<br>    val releaseDate: String,<br>    val title: String,<br>    val video: Boolean,<br>    val voteAverage: Double,<br>    val voteCount: Int,<br>    val page: Int,<br>    val insertedAt: Long = System.currentTimeMillis()<br>)</pre><blockquote>// data/local/entities/RemoteKeys.kt</blockquote><pre>@Entity(tableName = &quot;remote_keys&quot;)<br>data class RemoteKeys(<br>    @PrimaryKey val movieId: Int,<br>    val prevKey: Int?,<br>    val nextKey: Int?<br>)</pre><p>For writing the database operations like query we will create the dao classes, inside the dao package:</p><blockquote>// data/local/dao/MovieDao.kt</blockquote><pre>@Dao<br>interface MovieDao {<br>    @Query(&quot;SELECT * FROM movies ORDER BY page ASC, insertedAt ASC&quot;)<br>    fun getAllMoviesPaging(): PagingSource&lt;Int, MovieEntity&gt;<br><br>    @Query(&quot;SELECT * FROM movies ORDER BY page ASC, insertedAt ASC&quot;)<br>    fun getAllMovies(): Flow&lt;List&lt;MovieEntity&gt;&gt;<br><br>    @Insert(onConflict = OnConflictStrategy.REPLACE)<br>    suspend fun insertMovies(movies: List&lt;MovieEntity&gt;)<br><br>    @Query(&quot;DELETE FROM movies&quot;)<br>    suspend fun clearAllMovies()<br><br>    @Query(&quot;SELECT COUNT(*) FROM movies&quot;)<br>    suspend fun getMovieCount(): Int<br>}</pre><blockquote>// data/local/dao/RemoteKeysDao.kt</blockquote><pre>@Dao<br>interface RemoteKeysDao {<br>    @Query(&quot;SELECT * FROM remote_keys WHERE movieId = :movieId&quot;)<br>    suspend fun getRemoteKeysId(movieId: Int): RemoteKeys?<br><br>    @Insert(onConflict = OnConflictStrategy.REPLACE)<br>    suspend fun insertAll(remoteKey: List&lt;RemoteKeys&gt;)<br><br>    @Query(&quot;DELETE FROM remote_keys&quot;)<br>    suspend fun clearRemoteKeys()<br><br>    @Query(&quot;SELECT MAX(nextKey) FROM remote_keys&quot;)<br>    suspend fun getLastRemoteKey(): Int?<br>}</pre><p>Now, before completing the data layer, we need another model class in the domain layer, which will represent data to the presentation layer.</p><blockquote>// domain/model/Movie.kt</blockquote><pre>data class Movie(<br>    val id: Int,<br>    val adult: Boolean,<br>    val backdropPath: String?,<br>    val genreIds: List&lt;Int&gt;,<br>    val originalLanguage: String,<br>    val originalTitle: String,<br>    val overview: String,<br>    val popularity: Double,<br>    val posterPath: String?,<br>    val releaseDate: String,<br>    val title: String,<br>    val video: Boolean,<br>    val voteAverage: Double,<br>    val voteCount: Int<br>)</pre><p>Now, we need one wrapper in the data layer to convert the dto classes to Entity and Entity classesd to domain.</p><blockquote>// data/mappers/MovieMappers.kt</blockquote><pre>fun MovieDto.toEntity(page: Int): MovieEntity {<br>    return MovieEntity(<br>        id = id,<br>        adult = adult,<br>        backdropPath = backdropPath,<br>        genreIds = try {<br>            Gson().toJson(genreIds)<br>        } catch (e: Exception) {<br>            &quot;[]&quot;<br>        },<br>        originalLanguage = originalLanguage,<br>        originalTitle = originalTitle,<br>        overview = overview,<br>        popularity = popularity,<br>        posterPath = posterPath,<br>        releaseDate = releaseDate,<br>        title = title,<br>        video = video,<br>        voteAverage = voteAverage,<br>        voteCount = voteCount,<br>        page = page<br>    )<br>}<br><br>fun MovieEntity.toDomain(): Movie {<br>    return Movie(<br>        id = id,<br>        backdropPath = backdropPath,<br>        genreIds = Gson().fromJson(genreIds, object : TypeToken&lt;List&lt;Int&gt;&gt;() {}.type),<br>        overview = overview,<br>        posterPath = posterPath,<br>        releaseDate = releaseDate,<br>        title = title,<br>        voteAverage = voteAverage,<br>        adult = adult,<br>        video = video,<br>        originalLanguage = originalLanguage,<br>        voteCount = voteCount,<br>        originalTitle = originalTitle,<br>        popularity = popularity<br>    )<br>}</pre><p>Now, we need one mediator class which will make sure that the data will be saved to database at first from remote and then served to other layer. It also make sure the pagination works.</p><p>Here it is:</p><blockquote>// data/remote/mediator/MovieRemoteMediator.kt</blockquote><pre>@OptIn(ExperimentalPagingApi::class)<br>class MovieRemoteMediator(<br>    private val movieApi: MovieApi,<br>    private val movieDatabase: MovieDatabase<br>) : RemoteMediator&lt;Int, MovieEntity&gt;() {<br><br>     override suspend fun initialize(): InitializeAction {<br>        return InitializeAction.LAUNCH_INITIAL_REFRESH<br>    }<br><br><br>     override suspend fun load(<br>        loadType: LoadType,<br>        state: PagingState&lt;Int, MovieEntity&gt;<br>    ): MediatorResult {<br>        return try {<br>            val page = when (loadType) {<br>                LoadType.REFRESH -&gt; {<br>                    val remoteKeys = getRemoteKeyClosestToCurrentPosition(state)<br>                    remoteKeys?.nextKey?.minus(1) ?: 1<br>                }<br><br><br>                LoadType.PREPEND -&gt; {<br>                    val remoteKeys = getRemoteKeyForFirstItem(state)<br>                    val prevKey = remoteKeys?.prevKey<br>                    prevKey<br>                        ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)<br>                }<br><br>                LoadType.APPEND -&gt; {<br>                    val remoteKeys = getRemoteKeyForLastItem(state)<br>                    val nextKey = remoteKeys?.nextKey<br>                    nextKey<br>                        ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)<br>                }<br>            }<br><br><br>            val apiResponse = movieApi.getPopularMovies(<br>                language = &quot;en-US&quot;,<br>                page = page<br>            )<br><br>            val movies = apiResponse.results<br>            val endOfPaginationReached = movies.isEmpty() || page &gt;= apiResponse.totalPages<br>               movieDatabase.withTransaction {<br>                if (loadType == LoadType.REFRESH) {<br>                    movieDatabase.remoteKeysDao().clearRemoteKeys()<br>                    movieDatabase.movieDao().clearAllMovies()<br>                }<br>val prevKey = if (page &gt; 1) page - 1 else null<br>                val nextKey = if (endOfPaginationReached) null else page + 1<br>                val remoteKeys = movies.map {<br>                    RemoteKeys(movieId = it.id, prevKey = prevKey, nextKey = nextKey)<br>                }<br>                movieDatabase.remoteKeysDao().insertAll(remoteKeys)<br>                val movieEntities = movies.map { movieDto -&gt;<br>                    movieDto.toEntity(page)<br>                }<br>                movieDatabase.movieDao().insertMovies(movieEntities)<br>            }<br>            MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)<br>        } catch (e: Exception) {<br>            MediatorResult.Error(e)<br>        }<br>    }<br><br>    private suspend fun getRemoteKeyClosestToCurrentPosition(<br>        state: PagingState&lt;Int, MovieEntity&gt;<br>    ): RemoteKeys? {<br>        return state.anchorPosition?.let { position -&gt;<br>            state.closestItemToPosition(position)?.id?.let { movieId -&gt;<br>                movieDatabase.remoteKeysDao().getRemoteKeysId(movieId)<br>            }<br>        }<br>    }<br><br>    private suspend fun getRemoteKeyForFirstItem(<br>        state: PagingState&lt;Int, MovieEntity&gt;<br>    ): RemoteKeys? {<br>        return state.pages.firstOrNull {<br>            it.data.isNotEmpty()<br>        }?.data?.firstOrNull()?.let { movie -&gt;<br>            movieDatabase.remoteKeysDao().getRemoteKeysId(movie.id)<br>        }<br>    }<br><br>    private suspend fun getRemoteKeyForLastItem(<br>        state: PagingState&lt;Int, MovieEntity&gt;<br>    ): RemoteKeys? {<br>        return state.pages.lastOrNull {<br>            it.data.isNotEmpty()<br>        }?.data?.lastOrNull()?.let { movie -&gt;<br>            movieDatabase.remoteKeysDao().getRemoteKeysId(movie.id)<br>        }<br>    }<br><br>}</pre><p>Here, in the MovieRemoteMediator class, we need to understand some important facts:</p><h3>🔄 Paging 3 + RemoteMediator + Room = Single Source of Truth (SSOT) in Action</h3><p>The MovieRemoteMediator class is a <strong>bridge</strong> between the remote Movie API and local Room database, enabling paginated data loading while maintaining the <strong>Single Source of Truth (SSOT)</strong> principle. Here’s how it works step-by-step:</p><h3>✅ Key Points:</h3><h4>1. Single Source of Truth (SSOT)</h4><ul><li><strong>Local Room DB</strong> is the only source exposed to the UI.</li><li>Even when data comes from the network, it’s <strong>stored in the database first</strong>, and then fetched from there.</li><li>This ensures:</li><li>Offline support</li><li>Better testing</li><li>Decoupled UI from network layer</li></ul><h4>2. RemoteMediator Role</h4><ul><li>RemoteMediator&lt;Int, MovieEntity&gt; controls <strong>when and how</strong> remote data is fetched and cached locally.</li><li>It handles different load types:</li><li>REFRESH: On first launch or swipe to refresh.</li><li>PREPEND: When loading previous pages (not common for this API).</li><li>APPEND: When loading next pages.</li></ul><h4>3. Pagination Flow</h4><ul><li>Calculates the page to fetch based on current state (anchor, first, last items).</li><li>Fetches data from API (movieApi.getPopularMovies(page)).</li><li>Calculates prevKey and nextKey for tracking pagination.</li><li>Wraps DB operations in withTransaction { ... }:</li><li>Clears old data on REFRESH.</li><li>Saves RemoteKeys and mapped MovieEntity list into DB.</li><li>Returns MediatorResult.Success() or MediatorResult.Error() depending on the outcome.</li></ul><h4>4. RemoteKeys for Paging State</h4><ul><li>RemoteKeys table helps track which page came before/after each item.</li><li>Methods like getRemoteKeyForFirstItem, getRemoteKeyForLastItem, and getRemoteKeyClosestToCurrentPosition help Paging determine the next page to load.</li></ul><p>🔁 <strong>Lifecycle Example:</strong></p><blockquote>UI → PagingSource from Room → DB empty → triggers RemoteMediator<br>→ Fetches from API → Saves to DB → UI gets data from DB</blockquote><p>This cycle ensures:</p><ul><li>UI always observes <strong>local DB</strong>.</li><li>API is called <strong>only when needed</strong>.</li><li>Paging is <strong>seamless, efficient, and reactive</strong>.</li></ul><p>===============================================================</p><p>That’s it for this blog !!!</p><p>So, in this part we have completed our data layer by learning creating the <strong>model class (DTOs)</strong> , <strong>API call</strong> services interfaces, set up data caching by using <strong>RoomDB </strong>and creating necessary- <strong>Database, Entities, Dao classes</strong>. We have also learned how to use mediator to ensure the <strong>pagination </strong>and the data source (as data which comes from API are saved in local database and serves the UI layer, it ensures the <strong>Single Source of Truth</strong>).</p><p>In the next part, we will learn how will set-up our domain and presentation layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b018ac6284ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose + MVI: A Complete Guide with Movie API Integration (Part- I)]]></title>
            <link>https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-i-f45624a8405a?source=rss-1213a3158335------2</link>
            <guid isPermaLink="false">https://medium.com/p/f45624a8405a</guid>
            <category><![CDATA[mvi-architecture]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Asifulhaque]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 16:28:40 GMT</pubDate>
            <atom:updated>2025-07-12T17:45:12.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oDgWHG4CqdxScIpuz35vgw.png" /></figure><p>The purpose of this project is to demonstrate how to implement the <strong>MVI (Model-View-Intent)</strong> architecture pattern in a modern <strong>Android native Jetpack Compose</strong> application, integrated with a remote Movie API. This blog will walk you through the complete development process — from setting up the project and structuring packages to writing clean, modular, and testable code. Whether you’re just starting with MVI or looking to structure your Compose app better, this guide will provide a solid foundation.</p><h3><strong>Now, there is one question- why we should choose MVI architecture?</strong></h3><p>There are some points which verifies the benefit of MVI inside clean architecture:</p><ol><li><strong>Unidirectional Data Flow (UDF):</strong></li></ol><ul><li>MVI enforces a single direction of flow:<br> Event → ViewModel → State → UI</li><li>Makes logic easy to follow, debug, and test.</li></ul><p>2. <strong>Explicit UI Contracts</strong></p><ul><li>Every screen clearly defines:</li></ul><p>— What user can do → Event or Intent</p><p>— What UI can look like → State</p><ul><li>No hidden side effects or magical state changes.</li></ul><p>3. <strong>ViewModel Becomes the “Brain”</strong></p><ul><li>Handles all business logic by reacting to events and emitting states</li><li>UI (Jetpack Compose) simply <strong>observes state</strong> and renders accordingly</li></ul><p>4. <strong>Highly Testable</strong></p><ul><li>Easy to write tests:</li></ul><blockquote>“Given Event A, verify State B is emitted”</blockquote><ul><li>Pure, deterministic logic — no UI dependencies.</li></ul><p>5. <strong>Great Fit for Jetpack Compose</strong></p><ul><li>Compose is state-driven by design.</li><li>MVI’s emphasis on <strong>immutable </strong><strong>State and reactive rendering</strong> fits perfectly.</li></ul><p>6. <strong>Better Debugging &amp; Maintainability</strong></p><ul><li>You can log and trace the flow:</li></ul><blockquote>— Which event was triggered?</blockquote><blockquote>— What state did it produce?</blockquote><ul><li>Great for <strong>debugging</strong>, <strong>analytics</strong>, and <strong>feature isolation</strong></li></ul><p>So, in our project, we will use MVI architecture inside clean architecture to ensure a better skeleton of the project.</p><h3><strong>Project Structure:</strong></h3><pre>app<br>├── core<br>│ ├── common_components<br>│ ├── config<br>│ ├── constants<br>│ └── ui<br>├── data<br>│ ├── local<br>│ │ ├── dao<br>│ │ ├── database<br>│ │ └── entities<br>│ ├── remote<br>│ │ ├── api<br>│ │ ├── dto<br>│ │ ├── mediator<br>│ │ └── repository<br>│ └── mappers<br>├── di<br>├── domain<br>│ ├── model<br>│ ├── repository<br>│ └── usecase<br>├── presentation<br>│ ├── ui<br>│ └── viewmodel<br>│ ├── events<br>│ └── states<br>├── MainActivity.kt<br>└── MovieApp.kt</pre><p>To maintain clarity and scalability, the project follows a clean <strong>MVI (Model-View-Intent)</strong> architecture layered into three main components: data, domain, and presentation.</p><h3>core</h3><p>Contains reusable logic and base classes:</p><ul><li>common_components: Shared UI like error display.</li><li>config: Dynamic build configuration.</li><li>constants: API base URLs and endpoints.</li><li>ui: Generic UI states like DataState.</li></ul><h3>data</h3><p>Responsible for data handling — both local and remote.</p><ul><li><strong>local:</strong></li></ul><p>- dao: Room DAOs (e.g., MovieDao, RemoteKeysDao)</p><p>- database: Room setup including MovieDatabase and type converters</p><p>- entities: Room entities</p><ul><li><strong>remote:</strong></li></ul><p>- api: Retrofit API interface</p><p>- dto: Data Transfer Objects for API responses</p><p>- mediator: Paging 3 remote mediator</p><p>- repository: Implementation of the repository pattern</p><ul><li><strong>mappers:</strong></li></ul><p>Maps dto/entity ↔ domain model</p><h3>domain</h3><p>Represents the business logic layer:</p><ul><li>model: Domain-level models used across the app</li><li>repository: Repository interface (to be used by use cases)</li><li>usecase: Business use cases like GetMoviesUseCase</li></ul><h3>presentation</h3><p>This layer handles all UI and state management:</p><ul><li>ui: Composables like MovieScreen.kt</li><li>viewmodel:</li></ul><p>- events: User actions/events (MovieEvent)</p><p>- states: View state representation (MovieState)</p><p>- MovieViewModel: Business logic holder following MVI</p><h3>di</h3><p>that’s the Hilt dependency injection setup:</p><ul><li>NetworkModule: Provides Retrofit &amp; API dependencies</li><li>DatabaseModule: Provides Room dependencies</li><li>RepositoryModule: Provides repository instances</li></ul><p>====================================================</p><p>So, now let’s start with the project set-up with libs.versions.toml file.</p><p>libs.versions.toml</p><pre># Updated libs.toml file<br>[versions]<br>agp = &quot;8.6.0&quot;<br>kotlin = &quot;2.0.21&quot;<br>coreKtx = &quot;1.13.1&quot;<br>lifecycleRuntimeKtx = &quot;2.8.7&quot;<br>activityCompose = &quot;1.9.3&quot;<br>composeBom = &quot;2024.12.01&quot;<br>hilt = &quot;2.52&quot;<br>hiltNavigationCompose = &quot;1.2.0&quot;<br>retrofit = &quot;2.11.0&quot;<br>okhttp = &quot;4.12.0&quot;<br>room = &quot;2.6.1&quot;<br>coroutines = &quot;1.9.0&quot;<br>viewModelCompose = &quot;2.8.7&quot;<br>navigationCompose = &quot;2.8.5&quot;<br>gson = &quot;2.11.0&quot;<br>ksp = &quot;2.0.21-1.0.25&quot;<br>lifecycleRuntimeComposeAndroid = &quot;2.8.7&quot;<br>roomCommonJvm = &quot;2.6.1&quot;<br>databindingAdapters = &quot;8.11.0&quot;<br>paging = &quot;3.3.5&quot;<br>coil = &quot;2.7.0&quot;<br>materialIconsExtended = &quot;1.7.6&quot;<br><br><br>[libraries]<br>androidx-core-ktx = { group = &quot;androidx.core&quot;, name = &quot;core-ktx&quot;, version.ref = &quot;coreKtx&quot; }<br>androidx-lifecycle-runtime-ktx = { group = &quot;androidx.lifecycle&quot;, name = &quot;lifecycle-runtime-ktx&quot;, version.ref = &quot;lifecycleRuntimeKtx&quot; }<br>androidx-activity-compose = { group = &quot;androidx.activity&quot;, name = &quot;activity-compose&quot;, version.ref = &quot;activityCompose&quot; }<br>androidx-compose-bom = { group = &quot;androidx.compose&quot;, name = &quot;compose-bom&quot;, version.ref = &quot;composeBom&quot; }<br>androidx-ui = { group = &quot;androidx.compose.ui&quot;, name = &quot;ui&quot; }<br>androidx-ui-graphics = { group = &quot;androidx.compose.ui&quot;, name = &quot;ui-graphics&quot; }<br>androidx-ui-tooling = { group = &quot;androidx.compose.ui&quot;, name = &quot;ui-tooling&quot; }<br>androidx-ui-tooling-preview = { group = &quot;androidx.compose.ui&quot;, name = &quot;ui-tooling-preview&quot; }<br>androidx-ui-test-manifest = { group = &quot;androidx.compose.ui&quot;, name = &quot;ui-test-manifest&quot; }<br>androidx-material3 = { group = &quot;androidx.compose.material3&quot;, name = &quot;material3&quot; }<br>androidx-lifecycle-viewmodel-compose = { group = &quot;androidx.lifecycle&quot;, name = &quot;lifecycle-viewmodel-compose&quot;, version.ref = &quot;viewModelCompose&quot; }<br>androidx-navigation-compose = { group = &quot;androidx.navigation&quot;, name = &quot;navigation-compose&quot;, version.ref = &quot;navigationCompose&quot; }<br>androidx-lifecycle-runtime-compose = { group = &quot;androidx.lifecycle&quot;, name = &quot;lifecycle-runtime-compose&quot;, version.ref = &quot;lifecycleRuntimeComposeAndroid&quot; }<br><br># Material Icons Extended<br>androidx-material-icons-extended = { group = &quot;androidx.compose.material&quot;, name = &quot;material-icons-extended&quot;, version.ref = &quot;materialIconsExtended&quot; }<br><br># Hilt<br>hilt-android = { group = &quot;com.google.dagger&quot;, name = &quot;hilt-android&quot;, version.ref = &quot;hilt&quot; }<br>hilt-compiler = { group = &quot;com.google.dagger&quot;, name = &quot;hilt-compiler&quot;, version.ref = &quot;hilt&quot; }<br>hilt-navigation-compose = { group = &quot;androidx.hilt&quot;, name = &quot;hilt-navigation-compose&quot;, version.ref = &quot;hiltNavigationCompose&quot; }<br><br># Retrofit<br>retrofit = { group = &quot;com.squareup.retrofit2&quot;, name = &quot;retrofit&quot;, version.ref = &quot;retrofit&quot; }<br>retrofit-gson = { group = &quot;com.squareup.retrofit2&quot;, name = &quot;converter-gson&quot;, version.ref = &quot;retrofit&quot; }<br>okhttp = { group = &quot;com.squareup.okhttp3&quot;, name = &quot;okhttp&quot;, version.ref = &quot;okhttp&quot; }<br>okhttp-logging = { group = &quot;com.squareup.okhttp3&quot;, name = &quot;logging-interceptor&quot;, version.ref = &quot;okhttp&quot; }<br><br># Room<br>room-runtime = { group = &quot;androidx.room&quot;, name = &quot;room-runtime&quot;, version.ref = &quot;room&quot; }<br>room-compiler = { group = &quot;androidx.room&quot;, name = &quot;room-compiler&quot;, version.ref = &quot;room&quot; }<br>room-ktx = { group = &quot;androidx.room&quot;, name = &quot;room-ktx&quot;, version.ref = &quot;room&quot; }<br>room-paging = { group = &quot;androidx.room&quot;, name = &quot;room-paging&quot;, version.ref = &quot;room&quot; }<br><br># Paging<br>paging-runtime = { group = &quot;androidx.paging&quot;, name = &quot;paging-runtime&quot;, version.ref = &quot;paging&quot; }<br>paging-compose = { group = &quot;androidx.paging&quot;, name = &quot;paging-compose&quot;, version.ref = &quot;paging&quot; }<br><br># Coroutines<br>coroutines-core = { group = &quot;org.jetbrains.kotlinx&quot;, name = &quot;kotlinx-coroutines-core&quot;, version.ref = &quot;coroutines&quot; }<br>coroutines-android = { group = &quot;org.jetbrains.kotlinx&quot;, name = &quot;kotlinx-coroutines-android&quot;, version.ref = &quot;coroutines&quot; }<br><br># Gson<br>gson = { group = &quot;com.google.code.gson&quot;, name = &quot;gson&quot;, version.ref = &quot;gson&quot; }<br><br># Coil for image loading<br>coil-compose = { group = &quot;io.coil-kt&quot;, name = &quot;coil-compose&quot;, version.ref = &quot;coil&quot; }<br><br>[plugins]<br>android-application = { id = &quot;com.android.application&quot;, version.ref = &quot;agp&quot; }<br>jetbrains-kotlin-android = { id = &quot;org.jetbrains.kotlin.android&quot;, version.ref = &quot;kotlin&quot; }<br>hilt-android = { id = &quot;com.google.dagger.hilt.android&quot;, version.ref = &quot;hilt&quot; }<br>ksp = { id = &quot;com.google.devtools.ksp&quot;, version.ref = &quot;ksp&quot; }<br>compose-compiler = { id = &quot;org.jetbrains.kotlin.plugin.compose&quot;, version.ref = &quot;kotlin&quot; }</pre><p>That’s how your app-level gradle file may look like:</p><pre>import java.util.Properties      <br><br>  plugins {<br>            alias(libs.plugins.android.application)<br>            alias(libs.plugins.jetbrains.kotlin.android)<br>            alias(libs.plugins.hilt.android)<br>            alias(libs.plugins.ksp)<br>            alias(libs.plugins.compose.compiler)<br>        }<br><br>android {<br>    namespace = &quot;com.asif047.androidjetpackcomposemvihiltpagination&quot;<br>    compileSdk = 35<br><br>    defaultConfig {<br>        applicationId = &quot;com.asif047.androidjetpackcomposemvihiltpagination&quot;<br>        minSdk = 24<br>        targetSdk = 35<br>        versionCode = 1<br>        versionName = &quot;1.0&quot;<br><br>        testInstrumentationRunner = &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>        vectorDrawables {<br>            useSupportLibrary = true<br>        }<br>    }<br><br>    buildTypes {<br>        debug {<br>            buildConfigField(&quot;String&quot;, &quot;TMDB_API_KEY&quot;, &quot;\&quot;${getApiKey(&quot;TMDB_API_KEY_DEBUG&quot;)}\&quot;&quot;)<br>            buildConfigField(&quot;String&quot;, &quot;BASE_URL&quot;, &quot;\&quot;https://api.themoviedb.org/3/\&quot;&quot;)<br>        }<br>        release {<br>            buildConfigField(&quot;String&quot;, &quot;TMDB_API_KEY&quot;, &quot;\&quot;${getApiKey(&quot;TMDB_API_KEY_RELEASE&quot;)}\&quot;&quot;)<br>            buildConfigField(&quot;String&quot;, &quot;BASE_URL&quot;, &quot;\&quot;https://api.themoviedb.org/3/\&quot;&quot;)<br><br>            isMinifyEnabled = false<br>            proguardFiles(<br>                getDefaultProguardFile(&quot;proguard-android-optimize.txt&quot;),<br>                &quot;proguard-rules.pro&quot;<br>            )<br>        }<br>    }<br>    compileOptions {<br>        sourceCompatibility = JavaVersion.VERSION_11<br>        targetCompatibility = JavaVersion.VERSION_11<br>    }<br>    kotlinOptions {<br>        jvmTarget = &quot;11&quot;<br>    }<br>    buildFeatures {<br>        compose = true<br>        buildConfig = true<br>    }<br>    composeOptions {<br>        kotlinCompilerExtensionVersion = &quot;1.5.15&quot;<br>    }<br>    packaging {<br>        resources {<br>            excludes += &quot;/META-INF/{AL2.0,LGPL2.1}&quot;<br>        }<br>    }<br>}<br><br><br>dependencies {<br>    // Core Android<br>    implementation(libs.androidx.core.ktx)<br>    implementation(libs.androidx.lifecycle.runtime.ktx)<br>    implementation(libs.androidx.activity.compose)<br><br>    // Compose BOM and UI<br>    implementation(platform(libs.androidx.compose.bom))<br>    implementation(libs.androidx.ui)<br>    implementation(libs.androidx.ui.graphics)<br>    implementation(libs.androidx.ui.tooling.preview)<br>    implementation(libs.androidx.material3)<br>    implementation(libs.androidx.material.icons.extended)<br><br><br>    // Lifecycle and ViewModel<br>    implementation(libs.androidx.lifecycle.viewmodel.compose)<br>    implementation(libs.androidx.lifecycle.runtime.compose)<br>    implementation(libs.androidx.navigation.compose)<br><br>    // Hilt<br>    implementation(libs.hilt.android)<br>    implementation(libs.hilt.navigation.compose)<br>    ksp(libs.hilt.compiler)<br><br><br>    // Network<br>    implementation(libs.retrofit)<br>    implementation(libs.retrofit.gson)<br>    implementation(libs.okhttp)<br>    implementation(libs.okhttp.logging)<br><br><br>    // Database<br>    implementation(libs.room.runtime)<br>    implementation(libs.room.ktx)<br>    implementation(libs.room.paging)<br>    ksp(libs.room.compiler)<br><br>    // Paging<br>    implementation(libs.paging.runtime)<br>    implementation(libs.paging.compose)<br><br>    // Coroutines<br>    implementation(libs.coroutines.core)<br>    implementation(libs.coroutines.android)<br><br>    // JSON<br>    implementation(libs.gson)<br><br>    // Image Loading<br>    implementation(libs.coil.compose)<br><br>    // Debug<br>    debugImplementation(libs.androidx.ui.tooling)<br>    debugImplementation(libs.androidx.ui.test.manifest)<br>}<br><br><br>fun getApiKey(keyName: String): String {<br>    val localProperties = Properties()<br>    val localPropertiesFile = rootProject.file(&quot;local.properties&quot;)<br>    if (localPropertiesFile.exists()) {<br>        localProperties.load(localPropertiesFile.inputStream())<br>    }<br>    return localProperties.getProperty(keyName) ?: &quot;your api key&quot;<br>}</pre><p>That’s how the project-level gradle file will look like:</p><pre>plugins {<br>    alias(libs.plugins.android.application) apply false<br>    alias(libs.plugins.jetbrains.kotlin.android) apply false<br>    alias(libs.plugins.hilt.android) apply false<br>    alias(libs.plugins.ksp) apply false<br>}</pre><p>That’s it. Now, sync the gradle file and you will be good to go with coding.</p><p>In the next blog, we will set-up our core package and the data layer.</p><p>Next article link:<br><a href="https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-ii-b018ac6284ce">https://medium.com/@asifulhaque1144/jetpack-compose-mvi-a-complete-guide-with-movie-api-integration-part-ii-b018ac6284ce</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f45624a8405a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>