<?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 Sandip Pramanik on Medium]]></title>
        <description><![CDATA[Stories by Sandip Pramanik on Medium]]></description>
        <link>https://medium.com/@justsandip23?source=rss-405bdb8169e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ykt-lM19eae1UzO5</url>
            <title>Stories by Sandip Pramanik on Medium</title>
            <link>https://medium.com/@justsandip23?source=rss-405bdb8169e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:36:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@justsandip23/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[Environment Variables in Flutter Apps]]></title>
            <link>https://blog.stackademic.com/environment-variables-in-flutter-apps-db3d07999731?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3d07999731</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[envied]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[env]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 10:01:54 GMT</pubDate>
            <atom:updated>2024-08-26T00:44:38.495Z</atom:updated>
            <content:encoded><![CDATA[<h4>Secure and simplify your flutter app configuration with best practices and advanced tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D9k6GrSdvpVCVNLR" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Environment variables are key-value pairs used in software projects to configure applications outside of the source code. They are typically used to store configuration settings, such as database connection strings, API keys, and other sensitive information that should not be hard-coded into the application’s source code.</p><p>Environment variables are sensitive because they often contain confidential information that, if exposed, could compromise the security and integrity of the application. For example, exposing an API key can allow unauthorised users to access restricted services or data.</p><p>So our goal is to <strong>protect sensitive information by avoiding its inclusion in version control</strong>.</p><h3>Defining Secure Keys in a Dart File</h3><p>Below is an elaboration on this approach, including an example and a discussion of the pros and cons.</p><h3>1. Creating a Secure Configuration Dart File</h3><p>You can create a Dart file specifically for storing sensitive keys, such as secrets.dart. This file contains all the necessary constants or variables for your application:</p><pre>// lib/secrets.dart<br>class Secrets {<br>  static const String apiKey = &quot;YOUR_API_KEY_HERE&quot;;<br>  static const String clientSecret = &quot;YOUR_CLIENT_SECRET_HERE&quot;;<br>  static const String databasePassword = &quot;YOUR_DATABASE_PASSWORD_HERE&quot;;<br>}</pre><h3>2. Using .gitignore to Exclude Sensitive Files</h3><p>To ensure that your secrets.dart file does not get committed to your version control system (e.g., Git), you should add it to your .gitignore file:</p><pre># Ignore secrets file<br>lib/secrets.dart</pre><p>This method is straightforward and easy to implement without requiring additional set-up. Since the secrets are stored in plain Dart files, they can be easily accessed and used within your Flutter project.</p><p>But there are some disadvantages too -</p><ul><li>Vulnerable to man-in-the-middle attacks if the development environment is compromised.</li><li>Easy target for reverse engineering, exposing keys when the app is decompiled.</li><li>Hardcoding secrets limits flexibility for managing different environments or flavors.</li></ul><h3>Using dart-define for Environment Variables</h3><p>The dart-define option in Flutter is a powerful way to pass environment variables to your app at build time. This approach is especially useful for managing different configurations across various environments, such as development, staging, and production.</p><h3>How dart-define works</h3><p>With dart-define, you can pass key-value pairs directly from the command line when building or running your Flutter app. These key-value pairs are accessible in your Dart code via the String.fromEnvironment method.</p><p>Example Command:</p><pre>flutter run --dart-define=API_KEY=your_api_key_here</pre><p>Accessing in Code:</p><pre>const apiKey = String.fromEnvironment(&#39;API_KEY&#39;);</pre><h3>Benefits of Using dart-define</h3><ol><li>Easily pass different values for different environments without modifying your codebase. This makes it straightforward to maintain separate configurations for development, staging, and production.</li><li>The dart-define is ideal for continuous integration and deployment pipelines, where you can inject environment-specific variables during the build process.</li><li>Since the variables are passed at build time, they are not stored in the source code, reducing the risk of accidental exposure.</li></ol><h3>Considerations</h3><p>The dart-define is a flexible and secure way to manage environment-specific configurations in Flutter, making it a great choice for most production apps, especially when integrated into automated build pipelines.</p><p>However, if you find yourself managing a large number of variables, you may want to consider alternatives like dart-define-from-file for better organisation.</p><h3>Using dart-define-from-file for Environment Variables</h3><p>The dart-define-from-file feature was introduced as a way to streamline the process of managing environment variables by loading them from a JSON file during the build process.</p><p>However, this feature has faced significant issues and limitations, particularly when integrating with native platforms like iOS and Android.</p><p>How dart-define-from-file is Intended to Work</p><p>The idea behind dart-define-from-file is to allow developers to specify environment variables in a JSON file, which could then be passed to the Flutter app during the build.</p><p>Example JSON File: config.json</p><pre>{<br>  &quot;API_KEY&quot;: &quot;your_api_key_here&quot;,<br>  &quot;BASE_URL&quot;: &quot;&lt;https://api.example.com&gt;&quot;<br>}</pre><p>DO NOT forget to add the config json file in the .gitignore.</p><p>Next step, intended command:</p><pre>flutter run --dart-define-from-file=config.json</pre><p>In your Dart code, these variables would be accessible as follows:</p><pre>const apiKey = String.fromEnvironment(&#39;API_KEY&#39;);<br>const baseUrl = String.fromEnvironment(&#39;BASE_URL&#39;);</pre><p>⭐️ Important: Variables defined with --dart-define and --dart-define-from-file are only accessible on the Dart side, not on native platforms (iOS and Android), which complicates passing configuration values to native code.</p><p>From Flutter 3.16, this feature is preventing entries specified in the file from being written into Gradle configuration values or environment variables during the build process.</p><p>To read more in details, checkout the below 2 issues:</p><ol><li><a href="https://github.com/flutter/flutter/issues/138793"><strong>Concerns Regarding the Removal of </strong></a><a href="https://github.com/flutter/flutter/issues/138793"><strong>--dart-define-from-file Feature #138793</strong></a></li><li><a href="https://github.com/flutter/flutter/issues/139289"><strong>Allow to provide compile-time variables for native platforms from a file #139289</strong></a></li></ol><h3>Using envied for Secure Environment Variables</h3><p>The envied package is a popular solution in the Flutter ecosystem for managing environment variables securely. It allows you to define environment variables in a .env file and access them in your Flutter app with additional security features like encryption.</p><h3>How envied Works</h3><p>The envied package reads environment variables from a .env file at build time and generates a Dart file that contains these variables. This generated file is then used in your Flutter app to access the variables.</p><p>Example .env File:</p><pre>API_KEY=your_api_key_here<br>BASE_URL=https://api.example.com</pre><p>Create a dart class, say env.dart</p><pre>import &#39;package:envied/envied.dart&#39;;</pre><pre>part &#39;env.g.dart&#39;;<br>@envied<br>abstract class Env {<br>    @EnviedField(varName: &#39;API_KEY&#39;)<br>    static const String key = _Env.key;<br>    <br>    @EnviedField(varName: &#39;BASE_URL&#39;)<br>    static const String baseUrl = _Env.baseUrl;<br>}</pre><p>Run the build runner command to build you the generated class.</p><pre>dart run build_runner build</pre><p>Again, DO NOT forget to add these environment specific files in your .gitignore.</p><pre># Environment related files<br>.env<br>env.g.dart</pre><p>And, all set!</p><h3>What’s better with ENVied?</h3><ul><li>The envied package can encrypt sensitive values at, making it harder for attackers to extract them through reverse engineering. Read about obfuscation here - <a href="https://pub.dev/packages/envied#obfuscationencryption">https://pub.dev/packages/envied#obfuscationencryption</a>.</li><li>Since envied generates a Dart file, you get the benefits of type safety and can easily access your environment variables with autocompletion in your IDE.</li><li>With .env files, you can manage different environments (e.g., .env.dev, .env.prod) by creating separate files and loading them as needed. Here is a great example how to do that - <a href="https://github.com/petercinibulk/envied/blob/main/examples/envied_example/lib/app_env.dart">https://github.com/petercinibulk/envied/blob/main/examples/envied_example/lib/app_env.dart</a></li></ul><p>Want to know how GitHub CI/CD would work if the .env file and the env.g.dart files are inside .gitignore. Well, check out this repository and find out how it’s using GitHub Secrets to load the files during a job - <a href="https://github.com/thecodexhub/sudoku">https://github.com/thecodexhub/sudoku</a>.</p><h3>Conclusion</h3><p>Well, that’s a wrap. Thanks for hanging out till the end.</p><p>If you have any question or feedback, do let me know. The contact details are below -</p><p>🐙 <strong>GitHub:</strong> <a href="https://github.com/thecodexhub">thecodexhub</a><br>📷 <strong>Instagram:</strong> <a href="https://instagram.com/thecodexhub">@thecodexhub</a> <br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sandippramanik/">Sandip Pramanik</a><br>🐦 <strong>Twitter:</strong> <a href="https://x.com/thecodexhub">@thecodexhub</a><br>📧 <strong>Gmail:</strong> <a href="/service/mailto:thecodexhubofficial@gmail.com">thecodexhubofficial@gmail.com</a></p><p>Thank you again for joining this learning adventure. Your engagement matters!</p><p>Keep coding, stay curious, and remember — every line of code brings you closer to mastering app development.</p><p>Until next time, goodbye! 👋</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3d07999731" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/environment-variables-in-flutter-apps-db3d07999731">Environment Variables in Flutter Apps</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Xarvis CLI: Generate Production Ready Starter Template]]></title>
            <link>https://blog.stackademic.com/introducing-xarvis-cli-generate-production-ready-starter-template-a996da4c49c3?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a996da4c49c3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 18:42:38 GMT</pubDate>
            <atom:updated>2023-10-19T01:23:28.270Z</atom:updated>
            <content:encoded><![CDATA[<p>Xarvis CLI is a powerful command-line interface tool that allows developers to easily generate production-ready starter templates for their projects. With Xarvis CLI, you can kickstart your development process by generating a well-structured and optimised template that follows best practices.</p><p>By using Xarvis CLI, you save valuable time and effort in setting up a project from scratch. The generated starter template includes essential features and configurations, such as project structure, build tools, testing frameworks, and more. This ensures that your project starts off on the right foot, with all the necessary components in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oevwKzspC0LBlcRJ6eum5A.png" /></figure><h3>Limitations</h3><p>Before we dive into all the amazing features and functionality of Xarvis CLI, it is important to note that this is the first version of the tool. Currently, it only supports generating starter templates for ExpressJS applications using either JavaScript or TypeScript.</p><p>We greatly appreciate the community’s assistance in suggesting any ideas, recommendations or new features to help us improve and make this tool even more valuable.</p><h3>Features</h3><p>Xarvis CLI not only has a good architecture but also saves developers valuable time by providing preconfigured features and configurations. With Xarvis CLI, you don’t have to worry about building everything from scratch and potentially forgetting important components along the way.</p><p>While it may not be the only or the absolute best way of organising code, it offers a friendly starting point for building a codebase.</p><p>Now, let’s discuss some of the key features of the express starter templates:</p><h3>Linting rules with ESlint and Prettier</h3><p>Linting in production-ready apps ensures code quality and consistency. ESlint and Prettier form a powerful duo, catching code issues, enforcing coding standards, enhancing readability, and beautifying your code.</p><p>The .editorconfig file takes collaboration to the next level by ensuring all contributors follow the same coding style. This means that no matter who’s typing away on the keyboard, the codebase remains cohesive and easy to understand.</p><p>With pre-commit hooks driven by <a href="https://www.npmjs.com/package/lint-staged">lint-staged</a> and <a href="https://www.npmjs.com/package/husky">Husky</a>, every code change gets scrutinised before it’s added to the repository. This maintains code integrity and consistency, making life smoother for everyone involved in the project.</p><h3>ENV configuration and validation with Joi and dotenv</h3><p>In production-ready applications, environmental variables are essential for securely managing configurations, with <a href="https://www.npmjs.com/package/dotenv">dotenv</a> enabling easy management. Validation is upheld by <a href="https://www.npmjs.com/package/joi">Joi</a>, ensuring data integrity and app reliability.</p><p>The <a href="https://www.npmjs.com/package/cross-env">cross-env</a> facilitates consistent configuration across various platforms, mitigating compatibility issues throughout development, leading to a smoother workflow. <a href="https://github.com/kentcdodds/cross-env/issues/257">Learn more about why cross-env is needed, here.</a></p><p><a href="https://www.npmjs.com/package/pm2">PM2</a> serves as an effective load balancer, offering load distribution and automated restarts for enhanced application resilience. It also integrates robust system monitoring for a comprehensive production environment.</p><p>Ecosystem configuration files are pivotal in optimising app behaviour for different scenarios, providing the flexibility needed to fine-tune the production setup, adapt to varying requirements, and deliver top-notch performance. A sample ecosystem.config.json file is shown below:</p><pre>{<br>  &quot;apps&quot;: [<br>    {<br>      &quot;name&quot;: &quot;xarvis-express-js&quot;,<br>      &quot;script&quot;: &quot;src/index.js&quot;,<br>      &quot;instances&quot;: 1,<br>      &quot;autorestart&quot;: true,<br>      &quot;watch&quot;: false,<br>      &quot;time&quot;: true,<br>      &quot;env&quot;: {<br>        &quot;NODE_ENV&quot;: &quot;production&quot;<br>      }<br>    }<br>  ]<br>}</pre><h3>Secure http requests using helmet</h3><p>By enhancing HTTP security headers, Helmet provides a strong defense mechanism that helps prevent common web security threats. Its seamless integration with Express.js ensures a reliable, battle-tested security layer.</p><p><a href="https://www.npmjs.com/package/helmet">Learn more about helmet here</a>.</p><h3>Santitize request data with xss filters</h3><p>Using XSS Filters, your application can stay shielded from cross-site scripting (XSS) attacks, malicious threats, enhancing its overall security. These filters help clean up incoming data, minimising the chances of malicious code getting through.</p><p>This significantly strengthens your application’s security and safeguards it from typical security risks.</p><p><a href="https://en.wikipedia.org/wiki/Cross-site_scripting">Learn more about XSS Attack here</a>.</p><h3>Use gzip compression</h3><p>Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the <a href="https://www.npmjs.com/package/compression">compression</a> middleware for gzip compression in your Express app. For example:</p><pre>const compression = require(&#39;compression&#39;);<br>const express = require(&#39;express&#39;);<br>const app = express();<br>app.use(compression());</pre><h3>Enabling CORS and Preflight Requests</h3><p>When developing a web application, you often need to make requests to a different domain or origin. Cross-Origin Resource Sharing (CORS) and preflight requests facilitate this. They enable your app to access data from external sources securely.</p><p>By allowing CORS and preflight requests, you enhance your application’s ability to communicate with various services, making it more versatile and capable.</p><p><a href="https://www.npmjs.com/package/cors">Learn more about CORS and preflight here</a>.</p><h3>Effective Error Handling</h3><p>Error handling is a crucial aspect of production-ready applications. It ensures your application behaves gracefully in the face of issues.</p><p>With the right error handling middleware, your API can return consistent and informative error responses, making it easier to diagnose and fix problems. Moreover, unhandled exceptions are caught and handled appropriately, preventing unexpected crashes and downtime.</p><p>This ensures your application remains reliable and robust in real-world scenarios.</p><h3>Custom Logging with Winston and Morgan</h3><p>Custom logging using tools like Winston and Morgan is a smart practice for production-ready applications. It helps you track and understand what’s happening inside your application.</p><p>This makes debugging and monitoring more effective, especially when issues arise in a complex system. Customised log formats and levels allow you to tailor your logs to your specific needs, providing valuable insights into the behaviour of your application, improving maintainability, and making it easier to track down problems when they occur.</p><h3>Rate Limiting for Enhanced Security</h3><p>In a production environment, it’s crucial to guard against potential security threats and unauthorised access. Rate limiting, often implemented with packages like <a href="https://www.npmjs.com/package/express-rate-limit">express-rate-limit</a>, is a powerful measure. It restricts the number of requests a client can make to your application within a specific time frame.</p><p>Rate limiting is particularly valuable when it comes to mitigating the impact of repeated failed requests. It minimises the risk of brute force attacks and distributed denial of service (DDoS) attempts, helping to maintain the integrity of your services.</p><p>This proactive approach enhances security and safeguards your production-ready application from potential threats, making it a robust choice for your project.</p><h3>Unit Testing for Quality Assurance</h3><p>Ensuring that every piece of code functions as expected is crucial. This is where unit tests come into play. By using popular testing tools like Jest and Supertest, you can evaluate your application’s components individually, verifying that they work correctly.</p><p>While you may not have 100% test coverage yet, it’s a proactive step in the right direction. With further releases, the test coverage can be expanded to ensure that every aspect of your application meets the desired quality standards.</p><h3>Efficient GitHub Workflow</h3><p>Simplify your development process with GitHub Actions. On each push to the main branch, this streamlined workflow takes care of everything: code formatting, dependency management, and rigorous testing.</p><p><a href="https://docs.github.com/en/actions">Learn more about GitHub Workflow here</a>.</p><p>With the GitHub Action in place, you can focus on building a rock-solid production-ready application.</p><h3>How it works: Xarvis CLI</h3><p>Let’s dive into the nitty-gritty of Xarvis CLI. For an in-depth guide, you can refer to our <a href="https://github.com/thecodexhub/xarvis-cli#xarvis-cli">comprehensive README.</a></p><p>With Xarvis CLI, you have the power to effortlessly kickstart projects using our Xarvis Express templates. All it takes is a single command: <strong>xarvis create express-app</strong>. You&#39;ll be up and running with a production-ready application in no time.</p><p>Behind the scenes, Xarvis CLI is crafted with Node.js and TypeScript. We’ve harnessed the capabilities of Commander.js, making it a user-friendly, efficient, and highly versatile CLI tool. It’s designed to simplify your workflow and help you build robust applications seamlessly.</p><p>Whether you’re a seasoned developer or just starting out, Xarvis CLI is here to make your journey more enjoyable and productive. So, go ahead and explore what Xarvis CLI has to offer. Your next project is just a command away.</p><p>Discover More: <a href="https://github.com/thecodexhub/xarvis-cli">Xarvis CLI on GitHub</a></p><p>See it in action with Xarvis Express Template: <a href="https://github.com/thecodexhub/xarvis-express-js">Express JavaScript Template</a>, <a href="https://github.com/thecodexhub/xarvis-express-ts">Express TypeScript Template</a>.</p><p>Welcome to a world of easier, faster, and more efficient software development.</p><p>For questions, feedback, or connecting, find me here 👇</p><p>🐙 GitHub — <a href="https://github.com/thecodexhub"><strong><em>thecodexhub</em></strong></a><strong><em><br></em></strong>📷 Instagram — <a href="https://www.instagram.com/thecodexhub/"><strong><em>thecodexhub</em></strong></a><strong><em><br></em></strong>🔗 LinkedIn — <a href="https://www.linkedin.com/in/sandippramanik/"><strong><em>Sandip Pramanik</em></strong></a><strong><em><br></em></strong>🐦 Twitter — <a href="https://twitter.com/thecodexhub"><strong><em>thecodexhub</em></strong></a><strong><em><br></em></strong>📧 Gmail — <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>thecodexhubofficial@gmail.com</em></strong></a></p><p>Thank you for joining this learning adventure. Your engagement matters!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a996da4c49c3" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/introducing-xarvis-cli-generate-production-ready-starter-template-a996da4c49c3">Introducing Xarvis CLI: Generate Production Ready Starter Template</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extract Metadata from URL in Flutter]]></title>
            <link>https://blog.stackademic.com/how-to-extract-metadata-from-url-in-flutter-46d03df1ae7b?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/46d03df1ae7b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 10:41:41 GMT</pubDate>
            <atom:updated>2023-10-17T00:27:46.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZzyG90PYiyzJYo4" /><figcaption>Photo by <a href="https://unsplash.com/@olafval?utm_source=medium&amp;utm_medium=referral">Olaf Val</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to this article, where we’ll explore how to make your apps smarter by extracting useful information from web links.</p><p>Think of a scenario: You’re building an app, and you want it to display catchy information like article titles, descriptions, and images when users share web links. Or maybe you’re creating an app to help users manage their favorite links. To make these ideas work, we need to extract details from those links, and that’s where URL metadata extraction becomes crucial.</p><p>So, fasten your seatbelts as we are going to learn about the steps to build such a nice app, while still following good practices and error handling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_hv4XoZPsqC1n9oDNi01pQ.gif" /><figcaption>This is what we are going to build</figcaption></figure><h3>How to extract Metadata from URLs?</h3><p>Well, for this purpose we are going to use a powerful, free, and super-fast Link Scrapper API, the Jsonlink tool. It helps developers to extract structured data from any website or URL.</p><p>To learn more about Jsonlink, check out <a href="https://jsonlink.io/"><strong><em>https://jsonlink.io/</em></strong></a>.</p><p>Why Jsonlink, you ask? Well, it’s incredibly user-friendly and developer-focused. With its straightforward API endpoints, you can effortlessly retrieve data like titles, descriptions, and images from web links. This means no more complicated parsing or scraping code; it just takes care of the heavy lifting for you.</p><p>Now we know which API to use, let&#39;s start making our hands dirty by writing some code. And we will start by creating the model class. Before we start, let&#39;s have a quick look at our <strong>pubspec.yaml</strong> file.</p><pre>name: url_metadata_extract<br>description: A new Flutter project.<br>publish_to: &quot;none&quot;<br>version: 1.0.0+1<br><br>environment:<br>  sdk: &quot;&gt;=2.19.0 &lt;3.0.0&quot;<br><br>dependencies:<br>  bloc: ^8.1.2<br>  cupertino_icons: ^1.0.2<br>  equatable: ^2.0.5<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: ^8.1.3<br>  http: ^0.13.6<br>  json_annotation: ^4.8.1<br><br>dev_dependencies:<br>  build_runner: ^2.3.3<br>  flutter_lints: ^2.0.0<br>  flutter_test:<br>    sdk: flutter<br>  json_serializable: ^6.6.2<br><br>flutter:<br>  uses-material-design: true</pre><h3>Creating the URL Metadata Model</h3><p>Creating a well-structured model is key to efficiently managing data. To extract metadata from URLs, we’ll first define a model class — <strong>UrlMetadata</strong>. This class will help us organize and store the data we extract from web links.</p><p>Here’s a sneak peek at our <strong>UrlMetadata</strong> class:</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;package:json_annotation/json_annotation.dart&#39;;<br><br>part &#39;url_metadata.g.dart&#39;;<br><br>@JsonSerializable()<br>class UrlMetadata extends Equatable {<br>  const UrlMetadata({<br>    required this.title,<br>    required this.description,<br>    required this.imageUrls,<br>    required this.duration,<br>    required this.domain,<br>    required this.url,<br>  });<br><br>  factory UrlMetadata.fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      _$UrlMetadataFromJson(json);<br><br>  final String title;<br>  final String description;<br>  @JsonKey(name: &#39;images&#39;)<br>  final List&lt;String&gt; imageUrls;<br>  final int duration;<br>  final String domain;<br>  final String url;<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>        title,<br>        description,<br>        imageUrls,<br>        duration,<br>        domain,<br>        url,<br>      ];<br>}</pre><p>Our <strong>UrlMetadata</strong> class is equipped with all the necessary properties, such as <strong>title</strong>, <strong>description</strong>, <strong>imageUrls</strong>, <strong>duration</strong>, <strong>domain</strong>, and <strong>url</strong>, to store the extracted metadata.</p><p>It also includes the ability to convert JSON data into an instance of <strong>UrlMetadata</strong>, making it the perfect companion for our URL metadata extraction journey. For the <strong>fromJson</strong> method, we are going to use the <strong>build_runner</strong> package to generate the code for us. So, let&#39;s run our favorite command:</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><p>This command will generate a <strong>url_metadata.g.dart</strong> file, that contains the code for the <strong>fromJson</strong> method. In the next step, we are going to create a repository class that will take care of fetching the data from the API using the <strong>http</strong> package.</p><h3>Creating the URL Metadata Repository</h3><p>Now that we have our <strong>UrlMetadata</strong> model, it&#39;s time to set up the repository responsible for fetching and extracting metadata from a given URL. This repository will act as a bridge between our Flutter app and the Jsonlink API, making the process seamless.</p><p>Here’s a look at our <strong>UrlMetadataRepository</strong> class:</p><pre>import &#39;dart:convert&#39;;<br><br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;package:url_metadata_extract/url_metadata/url_metadata.dart&#39;;<br><br>class UrlMetadataRepository {<br>  UrlMetadataRepository({http.Client? httpClient})<br>      : _httpClient = httpClient ?? http.Client();<br><br>  final http.Client _httpClient;<br><br>  Future&lt;UrlMetadata&gt; extractUrlMetadata({required String url}) async {<br>    Uri uri;<br><br>    try {<br>      uri = Uri.parse(url);<br>    } on FormatException catch (_) {<br>      throw const UrlMetadataException(&#39;Invalid URL Format&#39;);<br>    }<br><br>    http.Response response;<br><br>    try {<br>      Uri requestUrl = Uri.parse(&#39;https://jsonlink.io/api/extract?url=$uri&#39;);<br>      response = await _httpClient.get(requestUrl);<br>    } on Exception catch (error) {<br>      throw UrlMetadataException(error.toString());<br>    }<br><br>    Map&lt;String, dynamic&gt; body;<br><br>    try {<br>      body = json.decode(response.body) as Map&lt;String, dynamic&gt;;<br>    } on Exception catch (_) {<br>      throw const UrlMetadataException(&#39;Unable to decode the JSON response&#39;);<br>    }<br><br>    if (response.statusCode != 200) {<br>      throw const UrlMetadataException(&#39;HTTP Exception occurred&#39;);<br>    }<br><br>    UrlMetadata metadata;<br><br>    try {<br>      metadata = UrlMetadata.fromJson(body);<br>    } on Exception catch (_) {<br>      throw const UrlMetadataException(&#39;Error while de-serializing the response&#39;);<br>    }<br><br>    return metadata;<br>  }<br>}</pre><p>The <strong>UrlMetadataRepository</strong> is a crucial part of our application. It utilizes the HTTP client to send requests to the Jsonlink API, fetches metadata, and handles errors gracefully.</p><p>With this repository, we’re well-equipped to fetch metadata from URLs and store them using our <strong>UrlMetadata</strong> model. This lays the foundation for extracting meaningful information from web links in our application.</p><p>Now we have our data source ready to be used by our states and UI. For this article, we are going to be utilizing Bloc as the state management library. So, let&#39;s start setting up the Bloc implementation step by step starting from defining the states.</p><h3>Setting Up the URL Metadata Bloc State</h3><p>To manage the state of our application as we interact with URLs and fetch metadata, we’ll be using the BLoC pattern (Business Logic Component). This will allow us to organize our code and handle state changes efficiently.</p><p>Here’s a look at the states we’ll be using in our <strong>UrlMetadataBloc</strong>:</p><pre>part of &#39;url_metadata_bloc.dart&#39;;<br><br>abstract class UrlMetadataState extends Equatable {<br>  const UrlMetadataState(this.url);<br>  final String url;<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [url];<br>}<br><br>class UrlMetadataInitial extends UrlMetadataState {<br>  const UrlMetadataInitial() : super(&#39;&#39;);<br>}<br><br>class UrlInUpdate extends UrlMetadataState {<br>  const UrlInUpdate(this.value) : super(value);<br>  final String value;<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [value];<br>}<br><br>class UrlMetadataLoading extends UrlMetadataState {<br>  const UrlMetadataLoading(super.url);<br>}<br><br>class UrlMetadataSuccess extends UrlMetadataState {<br>  const UrlMetadataSuccess(super.url, this.metadata);<br>  final UrlMetadata metadata;<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [metadata];<br>}<br><br>class UrlMetadataFailure extends UrlMetadataState {<br>  const UrlMetadataFailure(super.url, this.failure);<br>  final String failure;<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [failure];<br>}</pre><p>These states represent different stages of our URL metadata processing flow:</p><ul><li><strong>UrlMetadataInitial</strong>: The initial state.</li><li><strong>UrlInUpdate</strong>: When the user is entering or updating a URL.</li><li><strong>UrlMetadataLoading</strong>: While we&#39;re fetching metadata.</li><li><strong>UrlMetadataSuccess</strong>: When we successfully fetch metadata.</li><li><strong>UrlMetadataFailure</strong>: In case of any errors during the process.</li></ul><p>These states will help us manage the user interface and keep the user informed about what’s happening behind the scenes as they interact with the app. In the next steps, we’ll create the Bloc events and the logic implementations to handle these states and transitions.</p><h3>Managing User Interactions with Events</h3><p>To handle user interactions in our URL metadata application, we’ll use events to capture actions such as input changes and metadata fetching requests.</p><p>Here’s a look at the events we’ll be using in our <strong>UrlMetadataBloc</strong>:</p><pre>part of &#39;url_metadata_bloc.dart&#39;;<br><br>abstract class UrlMetadataEvent extends Equatable {<br>  const UrlMetadataEvent();<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class UrlChanged extends UrlMetadataEvent {<br>  const UrlChanged(this.value);<br>  final String value;<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [value];<br>}<br><br>class UrlMetadataSearched extends UrlMetadataEvent {<br>  const UrlMetadataSearched();<br>}</pre><p>These events represent user interactions:</p><ul><li><strong>UrlChanged</strong>: This event captures changes to the URL input field as the user types or updates the URL.</li><li><strong>UrlMetadataSearched</strong>: This event is triggered when the user clicks on the &quot;Extract Metadata&quot; button, indicating they want to fetch metadata for the provided URL.</li></ul><p>With these events, we can respond to user actions and manage the flow of our application. In the next steps, we’ll implement the Bloc logic to handle these events and update the application’s state accordingly.</p><h3>Managing State with the Bloc implementation</h3><p>To effectively manage the state of our URL metadata application, we’ll utilize the Bloc library. The code snippet below demonstrates how we’ll implement the <strong>UrlMetadataBloc</strong> to handle user events and convert the events into the application’s state accordingly:</p><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:bloc/bloc.dart&#39;;<br>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;package:url_metadata_extract/url_metadata/url_metadata.dart&#39;;<br><br>part &#39;url_metadata_event.dart&#39;;<br>part &#39;url_metadata_state.dart&#39;;<br><br>class UrlMetadataBloc extends Bloc&lt;UrlMetadataEvent, UrlMetadataState&gt; {<br>  UrlMetadataBloc({required UrlMetadataRepository urlMetadataRepository})<br>      : _urlMetadataRepository = urlMetadataRepository,<br>        super(const UrlMetadataInitial()) {<br>    on&lt;UrlChanged&gt;(_onUrlChanged);<br>    on&lt;UrlMetadataSearched&gt;(_onUrlMetadataSearched);<br>  }<br><br>  final UrlMetadataRepository _urlMetadataRepository;<br><br>  FutureOr&lt;void&gt; _onUrlChanged(<br>    UrlChanged event,<br>    Emitter&lt;UrlMetadataState&gt; emit,<br>  ) async {<br>    emit(UrlInUpdate(event.value));<br>  }<br><br>  FutureOr&lt;void&gt; _onUrlMetadataSearched(<br>    UrlMetadataSearched event,<br>    Emitter&lt;UrlMetadataState&gt; emit,<br>  ) async {<br>    emit(UrlMetadataLoading(state.url));<br><br>    try {<br>      final metadata = await _urlMetadataRepository.extractUrlMetadata(<br>        url: state.url,<br>      );<br>      emit(UrlMetadataSuccess(state.url, metadata));<br>    } on UrlMetadataException catch (e) {<br>      emit(UrlMetadataFailure(state.url, e.error));<br>    } catch (_) {<br>      emit(UrlMetadataFailure(state.url, &#39;Something unexpected occurred&#39;));<br>    }<br>  }<br>}</pre><p>In this implementation:</p><ul><li>We create a <strong>UrlMetadataBloc</strong> that extends the <strong>Bloc</strong> class. It takes a <strong>UrlMetadataRepository</strong> as a parameter to handle URL metadata extraction.</li><li>The constructor initializes the BLoC with the initial state, which is <strong>UrlMetadataInitial</strong>.</li><li>We define two event handlers: <strong>_onUrlChanged</strong> for capturing URL input changes and <strong>_onUrlMetadataSearched</strong> for handling metadata fetching requests.</li><li>Inside <strong>_onUrlChanged</strong>, we update the state to represent the URL being updated.</li><li>In <strong>_onUrlMetadataSearched</strong>, we transition to the loading state, attempt to fetch metadata using the repository and update the state accordingly based on the result. If there&#39;s an exception or an unexpected error, we transition to the failure state.</li></ul><p>With this Bloc implementation, we can seamlessly manage the state of our URL metadata application as users interact with it, providing a smooth and reliable user experience.</p><p>In this tutorial, it’s important to note that our primary focus is not on the intricacies of building a user interface (UI). Instead, we’ll emphasize the integration of the BLoC (Business Logic Component) pattern into our application to effectively manage state and user interactions.</p><p>Therefore, we won’t dive into every line of UI code but rather concentrate on the specific code segments responsible for user interaction and state management. This approach allows us to highlight the key aspects of integrating Bloc without getting caught up in UI-specific details.</p><h3>Implementing the View with Bloc</h3><p>In the view of our URL metadata extraction application, we’ll integrate the BLoC pattern using the <strong>BlocProvider</strong>. This will allow us to manage the state and user interactions effectively. Here&#39;s how we&#39;ll set up the view using the provided code snippet:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>class UrlMetadataPage extends StatelessWidget {<br>  const UrlMetadataPage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider&lt;UrlMetadataBloc&gt;(<br>      create: (context) =&gt; UrlMetadataBloc(<br>        urlMetadataRepository: context.read&lt;UrlMetadataRepository&gt;(),<br>      ),<br>      child: Scaffold(<br>        appBar: AppBar(<br>          title: const Text(&#39;Extract Metadata from URL&#39;),<br>        ),<br>        body: const Center(<br>          child: _UrlMetadataView(),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>In this code, we use <strong>BlocProvider</strong> to set up an <strong>UrlMetadataBloc</strong>, which handles user interactions and state for our page. The <strong>urlMetadataRepository</strong> is provided from the context, enabling interactions with the repository to fetch URL metadata.</p><p>In addition, we’ve already configured the repository provider to inject the URL metadata repository instance. Here’s the code for reference:</p><pre>class App extends StatelessWidget {<br>  const App({<br>    required UrlMetadataRepository urlMetadataRepository,<br>    super.key,<br>  }) : _urlMetadataRepository = urlMetadataRepository;<br><br>  final UrlMetadataRepository _urlMetadataRepository;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return RepositoryProvider&lt;UrlMetadataRepository&gt;.value(<br>      value: _urlMetadataRepository,<br>      child: const _AppView(),<br>    );<br>  }<br>}<br><br>class _AppView extends StatelessWidget {<br>  const _AppView();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;URL Metadata Extract&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.purple,<br>      ),<br>      home: UrlMetadataPage(),<br>    );<br>  }<br>}</pre><p>This ensures that the repository is available throughout the app and can be accessed by the <strong>UrlMetadataBloc</strong> when needed via <strong>context.read&lt;UrlMetadataRepository&gt;</strong>.</p><pre>BlocBuilder&lt;UrlMetadataBloc, UrlMetadataState&gt;(<br>  buildWhen: (previous, current) =&gt; previous.url != current.url,<br>  builder: (context, state) {<br>    return TextField(<br>      decoration: InputDecoration(<br>        border: OutlineInputBorder(<br>          borderRadius: BorderRadius.circular(4),<br>        ),<br>        hintText: &#39;Paste an URL here...&#39;,<br>      ),<br>      onChanged: (value) =&gt; context.read&lt;UrlMetadataBloc&gt;().add(<br>            UrlChanged(value),<br>          ),<br>    );<br>  },<br>),</pre><p>This <strong>TextField</strong> is wrapped in a <strong>BlocBuilder</strong> to reactively update the UI based on changes in the <strong>UrlMetadataState</strong>. When the user types or pastes a URL, the <strong>UrlChanged</strong> event is dispatched to the <strong>UrlMetadataBloc</strong>, allowing for real-time updates.</p><p>Let&#39;s talk about the submit button -</p><pre>class _ExtractMetadataSubmitButton extends StatelessWidget {<br>  const _ExtractMetadataSubmitButton();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocBuilder&lt;UrlMetadataBloc, UrlMetadataState&gt;(<br>      buildWhen: (previous, current) =&gt;<br>          previous.runtimeType != current.runtimeType,<br>      builder: (context, state) {<br>        return ElevatedButton(<br>          onPressed: state is! UrlMetadataLoading<br>              ? () =&gt; context.read&lt;UrlMetadataBloc&gt;().add(<br>                    const UrlMetadataSearched(),<br>                  )<br>              : null,<br>          child: state is UrlMetadataLoading<br>              ? const CircularProgressIndicator()<br>              : const Text(&#39;Extract Metadata from URL&#39;),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>This widget uses <strong>BlocBuilder</strong> to check the current state of the <strong>UrlMetadataState</strong> and displays either a button to extract metadata or a loading indicator based on the state.</p><p>Now let&#39;s build the card view that shows content based on the current state of the application.</p><pre>class _MetadataInfoView extends StatelessWidget {<br>  const _MetadataInfoView();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocBuilder&lt;UrlMetadataBloc, UrlMetadataState&gt;(<br>      buildWhen: (previous, current) =&gt;<br>          previous.runtimeType != current.runtimeType,<br>      builder: (context, state) {<br>        // We will continue building the rest here<br>      },<br>    );<br>  }<br>}</pre><p>We have created the <strong>_MetadataInfoView</strong> widget and wrapped it in a <strong>BlocBuilder</strong> to listen to changes in the <strong>UrlMetadataState</strong> and react accordingly. Let’s proceed with adding more code to this widget.</p><pre>return const Padding(<br>  padding: EdgeInsets.symmetric(horizontal: 60, vertical: 70),<br>  child: Text(<br>    &#39;Paste an URL in the text field above and hit the Extract Metadata button&#39;,<br>    textAlign: TextAlign.center,<br>    style: TextStyle(fontSize: 20, color: Colors.black45, height: 1.45),<br>  ),<br>);</pre><p>In this code, we’re displaying a message that instructs the user to paste a URL into the text field and press the “Extract Metadata” button. It provides guidance on how to use the app.</p><p>Next, we’ll discuss the case when the metadata is successful or failed.</p><pre>if (state is UrlMetadataFailure) {<br>  return Padding(<br>    padding: const EdgeInsets.symmetric(horizontal: 60, vertical: 70),<br>    child: Text(<br>      &#39;ERROR!!! ${state.failure}&#39;,<br>      textAlign: TextAlign.center,<br>      style: const TextStyle(<br>        fontSize: 20,<br>        color: Colors.black87,<br>        fontWeight: FontWeight.w600,<br>        height: 1.45,<br>      ),<br>    ),<br>  );<br>}</pre><p>In this code, when the state is of type <strong>UrlMetadataFailure</strong>, we display an error message with the specific failure reason. It helps the user understand why the metadata extraction failed.</p><p>Next, we’ll discuss the case when metadata is successfully extracted.</p><pre>if (state is UrlMetadataSuccess) {<br>  return Row(<br>    children: [<br>      ClipRRect(<br>        borderRadius: BorderRadius.circular(8),<br>        child: Image.network(state.metadata.imageUrls[0]),<br>      ),<br>      Expanded(<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.stretch,<br>          children: [<br>            Text(state.metadata.title),<br>            const SizedBox(height: 8),<br>            Text(state.metadata.description),<br>            const SizedBox(height: 16),<br>            Text(state.metadata.domain),<br>            const SizedBox(height: 16),<br>            Text(&#39;Time taken: ${state.metadata.duration}ms&#39;),<br>          ],<br>        ),<br>      ),<br>    ],<br>  );<br>}</pre><p>This code handles the case when the metadata extraction is successful, displaying the extracted metadata information such as the image, title, description, domain, and extraction duration.</p><h3>Conclusion</h3><p>In this tutorial, we’ve unveiled the magic of extracting URL metadata — a vital feature for crafting engaging and dynamic applications. From handling user interactions to fetching metadata, we’ve navigated the intricacies of this process step by step.</p><p>For a deeper dive into the code and examples, you can find all the project materials on this GitHub repository <a href="https://github.com/thecodexhub/flutter-projects/tree/main/url_metadata_extract"><strong>here</strong></a>. Feel free to explore, adapt, and incorporate these techniques into your Flutter applications.</p><p>For questions, feedback, or connecting, find me on LinkedIn, Instagram, Twitter, Gmail, or GitHub.</p><p>🐙 GitHub - <a href="https://github.com/thecodexhub"><strong><em>thecodexhub</em></strong></a><br>📷 Instagram - <a href="https://www.instagram.com/thecodexhub/"><strong><em>thecodexhub</em></strong></a><br>🔗 LinkedIn - <a href="https://www.linkedin.com/in/sandippramanik/"><strong><em>Sandip Pramanik</em></strong></a><br>🐦 Twitter - <a href="https://twitter.com/thecodexhub"><strong><em>thecodexhub</em></strong></a><br>📧 Gmail - <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>thecodexhubofficial@gmail.com</em></strong></a></p><p>Thank you for joining this learning adventure. Your engagement matters! If you have any questions or thoughts, feel free to reach out.</p><p>Thank you for joining us on this journey of URL metadata extraction in Flutter. Keep coding, keep innovating, and stay tuned for more exciting discoveries in the world of Flutter development. See you on the next adventure!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46d03df1ae7b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-extract-metadata-from-url-in-flutter-46d03df1ae7b">How to Extract Metadata from URL in Flutter</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Reactive Apps in Flutter with Streams and Bloc]]></title>
            <link>https://blog.stackademic.com/build-reactive-apps-in-flutter-with-streams-and-bloc-b26dac1e7910?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b26dac1e7910</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 16:32:01 GMT</pubDate>
            <atom:updated>2023-08-28T09:33:26.743Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use Streams and Bloc to build a reactive stopwatch app in Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bH97CMXRk4W6dvUI" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the ever-evolving landscape of mobile application development, user expectations continue to rise, demanding more dynamic, responsive, and engaging experiences. Flutter has rapidly gained traction among developers for its ability to craft visually appealing and performant cross-platform apps. However, as applications become more complex, maintaining clean and efficient code while managing the state can pose challenges.</p><p>This is where the concepts of reactive programming and architectural patterns like Bloc come into play. Reactive programming enables us to create apps that react to data changes in real time, ensuring that the user interface remains in sync with the underlying data. The Bloc (Business Logic Component) pattern provides a structured way to manage the flow of data within your application, promoting the separation of concerns and making your codebase more manageable and testable.</p><p>This article explores the fusion of two powerful techniques — reactive programming and the Bloc pattern — using a simple Stopwatch app example.</p><p>By the end of this tutorial, you’ll have a firm grasp of how to combine Flutter, Streams, and the Bloc pattern to build applications that not only meet but exceed modern user expectations for responsiveness and interactivity</p><p>So, what are you waiting for? Let’s get started!</p><h3>Table of Contents</h3><ul><li><a href="#4e0a">Getting Started with Reactive Programming</a></li><li><a href="#8c6b">Exploring the Bloc Pattern</a></li><li><a href="#b3a4">Creating a Ticker Class for Time Tracking</a></li><li><a href="#b43d">Implementing the Stopwatch Logic with Streams and Bloc</a><br>- <a href="#84da">Bloc State Definition - </a><a href="#84da">stopwatch_state.dart</a><br>- <a href="#0e39">Event handling setup with </a><a href="#0e39">stopwatch_event.dart</a><br>- <a href="#bb4c">Bloc implementation with Stream integration</a></li><li><a href="#6c5e">Real-time Interaction and UI Updates</a></li><li><a href="#b0fe">Conclusion</a></li></ul><h3>What is Reactive Programming?</h3><p><strong>Reactive programming is a declarative programming paradigm that is based on the idea of asynchronous event processing and data streams.</strong></p><p>In the realm of reactive programming, the cornerstone concept is <strong>Streams</strong>. Streams represent sequences of asynchronous events in Flutter, allowing developers to handle data-driven occurrences seamlessly. Leveraging the power of Streams, you can enable real-time updates in your app by reacting to events as they happen.</p><p>Here’s a glimpse of how you can work with Streams in Flutter:</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  final StreamController&lt;String&gt; controller = StreamController&lt;String&gt;();<br><br>  final subscription = controller.stream.listen((data) {<br>    print(&quot;Received: $data&quot;);<br>  });<br><br>  controller.sink.add(&quot;Hello, World!&quot;);<br>  <br>  // Don&#39;t forget to close the stream and controller when done<br>  subscription.cancel();<br>  controller.close();<br>}</pre><p>By understanding and embracing Streams, you’ll be equipped to synchronize different parts of your app efficiently, ensuring a responsive and dynamic user experience.</p><p>In the subsequent sections, we’ll delve deeper into applying this concept to our Stopwatch app example.</p><h3>Exploring the Bloc Pattern</h3><p>As you’re already acquainted with reactive programming fundamentals, let’s dive into the <strong>Bloc pattern</strong> — a potent architecture that facilitates efficient state management. The Bloc pattern compartmentalizes your app’s logic, ensuring a clean separation between the user interface and business logic. This modular approach fosters code reusability, testability, and maintainability.</p><p>In a nutshell, Blocs serve as intermediaries between UI components and data sources, handling events, processing them, and emitting updated states. This abstraction simplifies complex app logic, making it easier to manage state transitions and interactions. By following this pattern, you’re poised to create well-organized, responsive apps.</p><p>For those eager to delve deeper into the Bloc pattern, check out these resources:</p><ol><li><a href="https://bloclibrary.dev/">Official Flutter Bloc Library</a></li><li><a href="https://www.youtube.com/playlist?list=PLB6lc7nQ1n4jCBkrirvVGr5b8rC95VAQ5">Reso Coder’s “Bloc Library from Scratch” Series</a></li></ol><p>By incorporating the Bloc pattern, you’ll gain a powerful tool to streamline your app’s structure and manage state more effectively.</p><p>Now that we’ve grasped the essentials of reactive programming and the Bloc pattern, let’s embark on building our <strong>Reactive Stopwatch App</strong>. This practical example will illustrate how these concepts harmonize to create a fluid and dynamic user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0AzRlLU6s0ZZAcCGMGVsA.png" /></figure><p>Let’s begin by installing the required dependencies and establishing the project structure:</p><pre>name: stopwatch_app<br>description: Stopwatch app in Flutter with Streams and Bloc.<br>publish_to: &quot;none&quot;<br>version: 1.0.0+1<br><br>environment:<br>  sdk: &quot;&gt;=2.19.0 &lt;3.0.0&quot;<br><br>dependencies:<br>  bloc: ^8.1.2<br>  cupertino_icons: ^1.0.2<br>  equatable: ^2.0.5<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: ^8.1.3<br><br>dev_dependencies:<br>  flutter_lints: ^2.0.0<br>  flutter_test:<br>    sdk: flutter<br><br>flutter:<br>  uses-material-design: true</pre><pre>lib/<br>|-- stopwatch/<br>|  |-- bloc/<br>|  |  |-- stopwatch_bloc.dart<br>|  |  |-- stopwatch_event.dart<br>|  |  |-- stopwatch_state.dart<br>|  |-- view/<br>|  |  |-- stopwatch_page.dart<br>|  |-- stopwatch.dart<br>|  |-- ticker.dart<br>|-- app.dart<br>|-- main.dart</pre><p>In the bloc folder, the stopwatch_bloc.dart file will house the StopwatchBloc class, where we&#39;ll manage the app&#39;s state and behavior using the Bloc pattern. And the view folder will house the stopwatch_page.dart file, which will handle the user interface presentation and interaction.</p><p>By structuring our app this way, we maintain a clear separation of concerns and a tidy codebase.</p><p>Ready to see these concepts come together in a practical scenario? Let’s dive into the implementation and witness the transformation of our app.</p><h3>Creating a Ticker Class for Time Tracking</h3><p>Before we dive into building the core of our Stopwatch app with Bloc, let’s introduce a <strong>Ticker class</strong>. This class will play a crucial role in generating time ticks that we’ll utilize to update our Stopwatch.</p><pre>class Ticker {<br>  const Ticker();<br><br>  Stream&lt;int&gt; tick() =&gt;<br>      Stream&lt;int&gt;.periodic(const Duration(seconds: 1), (tick) =&gt; tick);<br>}</pre><p>The Ticker class encapsulates the concept of time intervals, emitting a stream of integers representing each tick. This class acts as a reliable time source, serving as the foundation for real-time updates within our app.</p><p>As we proceed, you’ll witness how this Ticker class seamlessly integrates with our Bloc implementation to create a dynamic and responsive Stopwatch.</p><h3>Implementing the Stopwatch Logic with Streams and Bloc</h3><p>In the upcoming sub-points, we’ll establish a Bloc state, design an event class, and construct the Bloc implementation. These steps will seamlessly integrate Streams and the Bloc pattern to create our dynamic Stopwatch app.</p><p>Let’s begin by defining the initial state of the Bloc.</p><h4>Bloc State Definition - stopwatch_state.dart</h4><p>Let’s lay the foundation for our Stopwatch Bloc by crafting the StopwatchState class. This class encapsulates essential information about the Stopwatch, including the total ticks, the current status (initial, in progress, or paused), and a list of recorded laps.</p><pre>part of &#39;stopwatch_bloc.dart&#39;;<br><br>enum StopwatchStatus { initial, inProgress, inPause }<br><br>class StopwatchState extends Equatable {<br>  const StopwatchState({<br>    this.ticks = 0,<br>    this.status = StopwatchStatus.initial,<br>    this.laps = const &lt;int&gt;[],<br>  });<br><br>  final int ticks;<br>  final StopwatchStatus status;<br>  final List&lt;int&gt; laps;<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [ticks, status, laps];<br><br>  StopwatchState copyWith({<br>    int? ticks,<br>    StopwatchStatus? status,<br>    List&lt;int&gt;? laps,<br>  }) {<br>    return StopwatchState(<br>      ticks: ticks ?? this.ticks,<br>      status: status ?? this.status,<br>      laps: laps ?? this.laps,<br>    );<br>  }<br>}</pre><p>The StopwatchState class serves as a snapshot of the app&#39;s state at any given time. It encompasses the number of ticks, the current status, and the recorded laps. As our Bloc processes events and time ticks, this state will evolve, paving the way for a responsive and interactive Stopwatch app.</p><p>To enhance ease of use, we’ve created extensions that allow convenient checks for the status of the Stopwatch.</p><pre>extension StopwatchStatusX on StopwatchStatus {<br>  bool get isInitial {<br>    return this == StopwatchStatus.initial;<br>  }<br><br>  bool get inProgress {<br>    return this == StopwatchStatus.inProgress;<br>  }<br><br>  bool get inPause {<br>    return this == StopwatchStatus.inPause;<br>  }<br>}</pre><h4>Event handling setup with stopwatch_event.dart</h4><p>To harness the power of the Bloc pattern in our Stopwatch app, we need to define several event classes that capture the actions and changes the app can undergo.</p><p>These events will serve as the triggers for state transitions within our Bloc.</p><pre>part of &#39;stopwatch_bloc.dart&#39;;<br><br>abstract class StopwatchEvent extends Equatable {<br>  const StopwatchEvent();<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class StopwatchStarted extends StopwatchEvent {<br>  const StopwatchStarted();<br>}<br><br>class StopwatchPaused extends StopwatchEvent {<br>  const StopwatchPaused();<br>}<br><br>class StopwatchResumed extends StopwatchEvent {<br>  const StopwatchResumed();<br>}<br><br>class StopwatchReset extends StopwatchEvent {<br>  const StopwatchReset();<br>}<br><br>class _StopwatchTicked extends StopwatchEvent {<br>  const _StopwatchTicked({required this.ticks});<br>  final int ticks;<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [ticks];<br>}<br><br>class StopwatchLapAdded extends StopwatchEvent {<br>  const StopwatchLapAdded();<br>}</pre><p>These event classes encapsulate the various actions the user can take with the Stopwatch app, including starting, pausing, resuming, and resetting.</p><p>Additionally, we’ve introduced an internal _StopwatchTicked event that handles the stream ticks from our Ticker class. Lastly, we have an event class for adding laps to the recorded laps list.</p><p>With these event classes defined, our app is equipped to respond to user actions and stream updates, translating them into meaningful state changes.</p><h4>Bloc implementation with Stream integration</h4><p>Let’s dive into the core of our Stopwatch Bloc. In this initial step, we’ll set up the basic structure for the Bloc class, along with a local variable to manage the stream subscription.</p><pre>class StopwatchBloc extends Bloc&lt;StopwatchEvent, StopwatchState&gt; {<br>  StopwatchBloc({Ticker? ticker})<br>      : _ticker = ticker ?? const Ticker(),<br>        super(const StopwatchState()) {<br>    on&lt;StopwatchStarted&gt;(_onStopwatchStarted);<br>    on&lt;StopwatchPaused&gt;(_onStopwatchPaused);<br>    on&lt;StopwatchResumed&gt;(_onStopwatchResumed);<br>    on&lt;StopwatchReset&gt;(_onStopwatchReset);<br>    on&lt;StopwatchLapAdded&gt;(_onStopwatchLapAdded);<br>    on&lt;_StopwatchTicked&gt;(_onStopwatchTicked);<br>  }<br><br>  final Ticker _ticker;<br><br>  StreamSubscription&lt;int&gt;? _stopwatchStreamSubscription;<br>}</pre><p>In this setup, we’re defining the StopwatchBloc class, extending Bloc and specifying the event type StopwatchEvent and the state type StopwatchState. We&#39;ve also introduced the _ticker variable, which defaults to the Ticker class we created earlier. This variable manages the time ticks stream.</p><p>We’ve included listeners for various event classes, which we’ll implement in the subsequent steps. Additionally, we’ve initialized the _stopwatchStreamSubscription variable to handle the stream subscription.</p><pre>FutureOr&lt;void&gt; _onStopwatchStarted(<br>  StopwatchStarted event,<br>  Emitter&lt;StopwatchState&gt; emit,<br>) async {<br>  _stopwatchStreamSubscription?.cancel();<br>  _stopwatchStreamSubscription = _ticker.tick().listen((ticks) {<br>    add(_StopwatchTicked(ticks: ticks));<br>  });<br>}<br><br>FutureOr&lt;void&gt; _onStopwatchTicked(<br>  _StopwatchTicked event,<br>  Emitter&lt;StopwatchState&gt; emit,<br>) async {<br>  emit(<br>    state.copyWith(<br>      status: StopwatchStatus.inProgress,<br>      ticks: event.ticks,<br>    ),<br>  );<br>}</pre><p>In the _onStopwatchStarted function, we ensure that any existing subscription is canceled to prevent potential issues. Then, we set up a new subscription to our ticker&#39;s time ticks stream. For each tick, we dispatch the _StopwatchTicked event, passing the tick count.</p><p>The _onStopwatchTicked function processes the incoming tick, updating the state to signify that the Stopwatch is in progress, while also reflecting the elapsed ticks.</p><p>This seamless interaction between event handling and state management demonstrates the beauty of the Bloc pattern in ensuring a coherent and responsive app experience.</p><p>Let’s finalize the implementation of our Stopwatch Bloc by adding the remaining event handlers.</p><pre>FutureOr&lt;void&gt; _onStopwatchPaused(<br>  StopwatchPaused event,<br>  Emitter&lt;StopwatchState&gt; emit,<br>) async {<br>  _stopwatchStreamSubscription?.pause();<br>  emit(state.copyWith(status: StopwatchStatus.inPause));<br>}<br><br>FutureOr&lt;void&gt; _onStopwatchResumed(<br>  StopwatchResumed event,<br>  Emitter&lt;StopwatchState&gt; emit,<br>) async {<br>  _stopwatchStreamSubscription?.resume();<br>  emit(state.copyWith(status: StopwatchStatus.inProgress));<br>}<br><br>FutureOr&lt;void&gt; _onStopwatchReset(<br>  StopwatchReset event,<br>  Emitter&lt;StopwatchState&gt; emit,<br>) async {<br>  _stopwatchStreamSubscription?.cancel();<br>  emit(const StopwatchState());<br>}<br><br>FutureOr&lt;void&gt; _onStopwatchLapAdded(<br>  StopwatchLapAdded event,<br>  Emitter&lt;StopwatchState&gt; emit,<br>) async {<br>  emit(state.copyWith(laps: [...state.laps, state.ticks]));<br>}</pre><p>In the _onStopwatchPaused function, we pause the stream subscription and update the state to indicate that the Stopwatch is in the pause state.</p><p>The _onStopwatchResumed function resumes the stream subscription and adjusts the state to signal that the Stopwatch is back in progress.</p><p>In the _onStopwatchReset function, we cancel the stream subscription and reset the state to its initial state, effectively resetting the Stopwatch.</p><p>Finally, the _onStopwatchLapAdded function handles adding a lap to the recorded laps list in the state.</p><p>Before wrapping up our Stopwatch Bloc implementation, it’s essential to properly close the stream subscription to prevent potential memory leaks.</p><pre>@override<br>Future&lt;void&gt; close() {<br>  _stopwatchStreamSubscription?.cancel();<br>  return super.close();<br>}</pre><p>By overriding the <strong>close</strong> method, we ensure that when the Bloc is closed, the stream subscription is also canceled. This safeguard guarantees that resources are freed and our app remains efficient and responsive.</p><p>With this final touch, our Stopwatch Bloc is now complete and ready to power a dynamic and reactive user experience.</p><h3>Real-time Interaction and UI Updates</h3><p>As we transition into building the user interface for our Stopwatch app, let’s first establish the connection to our Stopwatch Bloc using a BlocProvider.</p><pre>class StopwatchPage extends StatelessWidget {<br>  const StopwatchPage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider&lt;StopwatchBloc&gt;(<br>      create: (context) =&gt; StopwatchBloc(),<br>      child: const _StopwatchView(),<br>    );<br>  }<br>}</pre><p>In this code snippet, we create a StopwatchPage widget that sets up the StopwatchBloc using the BlocProvider. This provider ensures that the Bloc instance is available for the entire subtree, enabling our UI components to access and interact with the Bloc.</p><p><strong><em>Please note that this article focuses on integrating Streams and the Bloc pattern rather than delving into extensive UI design. As such, we’ll provide concise snippets of the UI components to complement the core concepts discussed.</em></strong></p><p>As we venture into crafting the UI for our Stopwatch app, let’s start with a concise snippet for displaying the elapsed time as hours, minutes, and seconds.</p><pre>class _StopwatchText extends StatelessWidget {<br>  const _StopwatchText();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final totalTicks = context.select((StopwatchBloc bloc) =&gt; bloc.state.ticks);<br>    final hoursStr = &#39;${(totalTicks / 3600).floor()}&#39;.padLeft(2, &#39;0&#39;);<br>    final minutesStr = &#39;${((totalTicks / 60) % 60).floor()}&#39;.padLeft(2, &#39;0&#39;);<br>    final secondsStr = &#39;${(totalTicks % 60).floor()}&#39;.padLeft(2, &#39;0&#39;);<br><br>    return Text(<br>      &#39;$hoursStr:$minutesStr:$secondsStr&#39;,<br>    );<br>  }<br>}</pre><p>In the _StopwatchText widget, we utilize the context.select method to obtain the current total ticks from the StopwatchBloc&#39;s state. We then convert the ticks into hours, minutes, and seconds using simple calculations.</p><p>Please keep in mind that the provided UI snippets are high-level representations to complement the core concepts. For a comprehensive understanding and to explore the complete codebase of this example Stopwatch app, you can find the entire implementation in our <a href="https://github.com/thecodexhub/flutter-projects/tree/main/stopwatch_app"><strong>GitHub repository</strong></a>.</p><p>Continuing with the UI construction, let’s showcase the code snippet for displaying lap times in a concise manner.</p><pre>class _StopwatchLapList extends StatelessWidget {<br>  const _StopwatchLapList();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final laps = context.select((StopwatchBloc bloc) =&gt; bloc.state.laps);<br><br>    return ListView.separated(<br>      itemCount: laps.length,<br>      separatorBuilder: (_, __) =&gt; const SizedBox(height: 8),<br>      itemBuilder: (context, index) {<br>        final totalTicks = laps[index];<br>        final hh = &#39;${(totalTicks / 3600).floor()}&#39;.padLeft(2, &#39;0&#39;);<br>        final mm = &#39;${((totalTicks / 60) % 60).floor()}&#39;.padLeft(2, &#39;0&#39;);<br>        final ss = &#39;${(totalTicks % 60).floor()}&#39;.padLeft(2, &#39;0&#39;);<br><br>        return Text(<br>          &#39;#${index + 1}      $hh:$mm:$ss&#39;,<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>In the _StopwatchLapList widget, again we use the context.select method to retrieve the recorded laps from the StopwatchBloc&#39;s state. We then construct a ListView.separated to display each lap time, formatted as hours, minutes, and seconds. Each lap is presented with an index, followed by the formatted time.</p><p>Let’s start working on the action buttons. Depending on the current state, we’ll show different sets of buttons and different sets of functionalities.</p><pre>class _StopwatchActionButtons extends StatelessWidget {<br>  const _StopwatchActionButtons();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocBuilder&lt;StopwatchBloc, StopwatchState&gt;(<br>      buildWhen: (previous, current) =&gt; previous.status != current.status,<br>      builder: (context, state) {<br>        // ...<br>      },<br>    );<br>  }<br>}</pre><p>In this part, we’re utilizing the BlocBuilder widget from the flutter_bloc library. The buildWhen argument is used to determine whether the builder function should be called based on changes in the state. In this case, we’re only rebuilding the UI when the status property of the state changes.</p><pre>if (state.status.isInitial) {<br>  return FloatingActionButton.extended(<br>    key: const Key(&#39;stopwatchInitial_startButton&#39;),<br>    onPressed: () =&gt; context.read&lt;StopwatchBloc&gt;().add(<br>      const StopwatchStarted(),<br>    ),<br>    label: Row(<br>      children: const [<br>        Icon(Icons.play_arrow),<br>        SizedBox(width: 4),<br>        Text(&#39;Start stopwatch&#39;),<br>      ],<br>    ),<br>  );<br>}</pre><p>Here, we use BlocBuilder ’s builder method to display a “Start” button when the stopwatch is in its initial state. The button, a FloatingActionButton.extended, triggers the StopwatchStarted event, initializing the stopwatch.</p><pre>if (state.status.inProgress) {<br>  return Row(<br>    mainAxisAlignment: MainAxisAlignment.spaceAround,<br>    children: [<br>      FloatingActionButton.small(<br>        key: const Key(&#39;stopwatchInProgress_resetButton&#39;),<br>        onPressed: () =&gt; context.read&lt;StopwatchBloc&gt;().add(<br>              const StopwatchReset(),<br>            ),<br>        child: const Icon(Icons.rotate_left),<br>      ),<br>      FloatingActionButton.extended(<br>        key: const Key(&#39;stopwatchInProgress_pauseButton&#39;),<br>        onPressed: () =&gt; context.read&lt;StopwatchBloc&gt;().add(<br>              const StopwatchPaused(),<br>            ),<br>        label: Row(<br>          children: const [<br>            Icon(Icons.pause),<br>            SizedBox(width: 4),<br>            Text(&#39;Pause stopwatch&#39;),<br>          ],<br>        ),<br>      ),<br>      FloatingActionButton.small(<br>        key: const Key(&#39;stopwatchInProgress_lapCreateButton&#39;),<br>        onPressed: () =&gt; context.read&lt;StopwatchBloc&gt;().add(<br>              const StopwatchLapAdded(),<br>            ),<br>        child: const Icon(Icons.timer_outlined),<br>      ),<br>    ],<br>  );<br>}</pre><p>When the stopwatch is in progress, this code snippet generates a row of action buttons. These buttons allow users to perform specific actions on the stopwatch:</p><ol><li><strong>Reset Button:</strong> Resets the stopwatch when pressed by triggering the StopwatchReset event.</li><li><strong>Pause Button:</strong> Pauses the stopwatch when pressed by triggering the StopwatchPaused event.</li><li><strong>Create Lap Button:</strong> Records a lap time when pressed by triggering the StopwatchLapAdded event.</li></ol><pre>if (state.status.inPause) {<br>  return Row(<br>    mainAxisAlignment: MainAxisAlignment.spaceAround,<br>    children: [<br>      FloatingActionButton.small(<br>        key: const Key(&#39;stopwatchInPause_resetButton&#39;),<br>        onPressed: () =&gt; context.read&lt;StopwatchBloc&gt;().add(<br>              const StopwatchReset(),<br>            ),<br>        child: const Icon(Icons.rotate_left),<br>      ),<br>      FloatingActionButton.extended(<br>        key: const Key(&#39;stopwatchInPause_resumeButton&#39;),<br>        onPressed: () =&gt; context.read&lt;StopwatchBloc&gt;().add(<br>              const StopwatchResumed(),<br>            ),<br>        label: Row(<br>          children: const [<br>            Icon(Icons.play_arrow),<br>            SizedBox(width: 4),<br>            Text(&#39;Resume stopwatch&#39;),<br>          ],<br>        ),<br>      ),<br>    ],<br>  );<br>}</pre><p>When the stopwatch status is in pause, this part of the code creates a row of action buttons with specific functions:</p><ol><li><strong>Reset Button:</strong> Resets the stopwatch when pressed by triggering the StopwatchReset event.</li><li><strong>Resume Button:</strong> Resumes the stopwatch from the paused state when pressed, re-initiating the stopwatch.</li></ol><p>This set of buttons provides options to reset the stopwatch or to seamlessly transition back into active time tracking.</p><p>With this, we’ve navigated through all the essential steps required to construct a fully functional stopwatch app, harnessing the power of reactive programming through Streams and the Bloc pattern.</p><h3>Conclusion</h3><p>In this tutorial, we’ve covered the entire process of building a functional stopwatch app using reactive programming with Streams and the Bloc pattern in Flutter. From foundational concepts to intricate UI design, we’ve journeyed through the essentials.</p><p>All code snippets and resources are available in the <a href="https://github.com/thecodexhub/flutter-projects/tree/main/stopwatch_app"><strong>GitHub repository</strong></a>. Feel free to explore, experiment, and build upon them. If you found this tutorial helpful, a like and comment would be greatly appreciated!</p><p>For questions, feedback, or connecting, find me on LinkedIn, Instagram, Twitter, Gmail, or GitHub.</p><p>🐙 <strong>GitHub:</strong> <a href="https://github.com/thecodexhub">thecodexhub</a> <br>📷 <strong>Instagram:</strong> <a href="https://www.instagram.com/thecodexhub/">@thecodexhub</a><br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sandippramanik/">Sandip Pramanik</a> <br>🐦 <strong>Twitter:</strong> <a href="https://twitter.com/thecodexhub">@thecodexhub</a> <br>📧 <strong>Gmail:</strong><a href="/service/mailto:thecodexhubofficial@gmail.com"> thecodexhubofficial@gmail.com</a></p><p>Thank you for joining this learning adventure. Your engagement matters! If you have any questions or thoughts, feel free to reach out.</p><p>Keep coding, stay curious, and remember - every line of code brings you closer to mastering app development.</p><p>Until next time, goodbye and see you soon! 👋</p><p><em>Thank you for reading until the end. Please consider following the writer and this publication. Visit </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b26dac1e7910" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/build-reactive-apps-in-flutter-with-streams-and-bloc-b26dac1e7910">Build Reactive Apps in Flutter with Streams and Bloc</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart Frog - Fast & Minimalistic Backend Framework for Dart]]></title>
            <link>https://towardsdev.com/dart-frog-fast-minimalistic-backend-framework-for-dart-fcfca966c976?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcfca966c976</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart-frog]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 10:52:25 GMT</pubDate>
            <atom:updated>2022-09-13T15:21:38.939Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the Dart Frog framework with an example Books Directory application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uPkpPm0ZjG6YOQR2" /><figcaption>Photo by <a href="https://unsplash.com/@lazizli?utm_source=medium&amp;utm_medium=referral">Lala Azizli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In software engineering, the terms front-end and backend refer to the separation of concerns between the presentation layer (front-end), and the data access layer (backend) of a piece of software, or the physical infrastructure or hardware.</p><p>Activities, like writing APIs, interacting with databases, creating libraries, and working with system components without user interfaces or even systems of scientific programming, are included in the backend.</p><p><a href="https://dartfrog.vgv.dev/"><strong>Dart Frog</strong></a> is a fast, minimalistic backend framework on Dart made by the <a href="https://verygood.ventures/"><strong>VGVentures</strong></a> team. It can create new endpoints in just a few lines and iterate blazingly fast with the hot reload feature.</p><p>With its simple core and minimal API surface, it reduces ramp-up time. Also, it optimizes the process of building backends that aggregate, compose, and normalize data from multiple sources.</p><h3>Table of Contents</h3><ul><li><a href="#fbd4"><em>Getting Started with Dart Frog</em></a></li><li><a href="#2bc8"><em>Books Directory - Made with Dart Frog</em></a></li><li><a href="#bec7"><em>First Step - Create a new project</em></a></li><li><a href="#b5b9"><em>Create the data source - BooksDataSource</em></a></li><li><a href="#ceeb"><em>Add the required Dependencies</em></a></li><li><a href="#0417"><em>Create the Book model</em></a></li><li><a href="#8605"><em>Run the build_runner to Generate Serialization Code</em></a></li><li><a href="#11bd"><em>Complete the DataSource</em></a></li><li><a href="#1107"><em>Add BooksDataSource as Dependency</em></a></li><li><a href="#a361"><em>Create the Middlewares - Logger, Dependency Injection</em></a></li><li><a href="#9cfb"><em>Create the /books route</em></a></li><li><a href="#21f2"><em>Complete the GET and POST methods</em></a></li><li><a href="#29bc"><em>Create the /books/[id] route</em></a></li><li><a href="#b77d"><em>Complete the GET, PUT and DELETE methods</em></a></li></ul><h3>Getting Started with Dart Frog</h3><p>The easiest way to get started is by installing <a href="https://pub.dev/packages/dart_frog_cli"><em>dart_frog_cli</em></a><strong> </strong>from <a href="https://pub.dev/"><em>pub.dev</em></a>.</p><pre><em>$ dart pub global activate dart_frog_cli</em></pre><p>In the next step, check out the official documentation to learn the basics of Dart Frog. Once you go through the <a href="https://dartfrog.vgv.dev/docs/basics/routes"><strong>Routing</strong></a>, <a href="https://dartfrog.vgv.dev/docs/basics/middleware"><strong>Middleware</strong></a>, and <a href="https://dartfrog.vgv.dev/docs/basics/dependency-injection"><strong>Dependency Injection</strong></a> concepts from the docs, you are ready to move forward with this tutorial.</p><p>This tutorial doesn’t cover these above-said concepts in depth, but you’ll also get an overview of them along the way. This article is focused on creating a backend application with Dart Frog.</p><p>Don’t worry if you have never worked with any kind of backend framework before. We will try to discuss as much in detail as possible.</p><h3>Books Directory - Made with Dart Frog</h3><p>In this tutorial, we are going to build a RESTful books directory API, i.e., endpoints that can create a new book record, get/read a list containing all the books, get a particular book with a provided id, and even update and delete a book with the specified id.</p><p>Let’s first see the routes that we need to handle for the CRUD (Create, Read, Update, Delete) operations of books.</p><ul><li><strong>GET</strong> /books → returns the list of books stored</li><li><strong>POST</strong> /books → creates and stores a new book record</li><li><strong>GET</strong> /books/[id] → returns the book with the specified id</li><li><strong>PUT</strong> /books/[id] → updates the book with the specified id</li><li><strong>DELETE</strong> /books/[id] → deletes the book with the specified id</li></ul><p>Altogether there are two endpoints to trigger the basic CRUD operations on a list of books. Note that we are going to use Postman as the API Client to test our endpoints. You can choose any other platform that feels convenient to you.</p><p>Without further delay, let’s start working on this project.</p><h3>First Step - Create a new project</h3><p>Let’s create a new Dart Frog app using the Dart Frog CLI. Open your preferred terminal and run the following command to create a new project.</p><pre><em>$ dart_frog create books_directory</em></pre><p>After a few seconds, your app will be ready and you can run the server using these simple commands.</p><pre><em>$ cd books_directory<br>$ dart_frog dev</em></pre><p>The server will default start listening to your localhost on port 8080. But, you can configure the port to listen using the <em>--port</em> option.</p><pre><em>$ dart_frog dev --port=8081</em></pre><p>Now, you can go to your API Client, here Postman, to test the default endpoint, already provided in the starter project. If everything works as expected, you will see the output “<strong>Welcome to Dart Frog!</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5cD2fyfF4IlVc6AIHsKFQ.png" /><figcaption>http://localhost:8081/ → Welcome to Dart Frog!</figcaption></figure><h3>Create the data source - BooksDataSource</h3><p>Now that the application is up and running, we must create an abstraction for the books data source that will expose APIs for C.R.U.D. operations on a list of books. We can develop the books data source as a package because it is not closely tied to our Dart Frog application.</p><p>One way to modularize a project is to divide it into one or more packages, which can effectively structure our application, maintain clear boundaries, and improve maintainability and reusability.</p><p>Throughout this tutorial, we’ll make use of <a href="https://pub.dev/packages/very_good_cli"><em>package:very_good_cli</em></a> to assist us easily generating new packages.</p><p>If you don’t have very_good_cli installed in your system, please follow the <a href="https://pub.dev/packages/very_good_cli#installing"><em>installation instructions</em></a> from the package readme before proceeding further.</p><p>Create a new directory with the name <em>packages</em>. After that, we can create our package <em>books_data_source</em> inside the <em>packages</em> directory.</p><pre><em>$ very_good create books_data_source -t dart_pkg --desc “In-memory implementation for managing Books data source interface.”</em></pre><h4>Add the required Dependencies</h4><p>Let’s start by adding relevant dependencies in the <em>pubspec.yaml</em> file of the <em>books_data_source</em> package and install them using <em>dart pub get</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24fb497ed75a6962ad5bb50466fe0e22/href">https://medium.com/media/24fb497ed75a6962ad5bb50466fe0e22/href</a></iframe><h4>Create the Book model</h4><p>Let’s define our book model now, which will be a straightforward Dart class that represents a single book object. The contents of <em>lib/src/models/book.dart</em> should be as shown below.</p><p>To handle the generation of the code to (de)serialize to and from JSON, the Book class makes use of <a href="https://pub.dev/packages/json_serializable"><em>package:json_serializable</em></a>. And it extends <a href="https://pub.dev/packages/equatable"><em>package:equatable</em></a> to implement value-based equality so that Book instances can be compared on values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a4255c4213979a0e3787940b9bfeeec/href">https://medium.com/media/0a4255c4213979a0e3787940b9bfeeec/href</a></iframe><h4>Run the build_runner to Generate Serialization Code</h4><p>Next, we need to generate the necessary serialization code using the <a href="https://pub.dev/packages/build_runner"><em>package:build_runner</em></a>.</p><pre><em>$ dart run build_runner build --delete-conflicting-outputs</em></pre><p>At this point, there shouldn’t be any errors or warnings in our code, and we should be able to see that the <em>todos.g.dart</em> file was generated.</p><h4>Complete the DataSource</h4><p>The last thing we need to do in the <em>books_data_source</em> package is to define the <em>BooksDataSource</em> class.</p><p>It’s going to be a concrete implementation of how the books are going to be stored and accessed from an in-memory data structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb9b3f4cf5c6b10ada82da855f108f2/href">https://medium.com/media/3bb9b3f4cf5c6b10ada82da855f108f2/href</a></iframe><p>There you go! We have finished creating the data sources for our Dart Frog application, and now we can begin developing the actual Dart Frog application!</p><h3>Add BooksDataSource as Dependency</h3><p>The root <em>pubspec.yaml</em> needs to be updated to include the <em>books_data_source</em> dependency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07e108760139519775f916f8ddae884a/href">https://medium.com/media/07e108760139519775f916f8ddae884a/href</a></iframe><p>Then install the package using <em>dart pub get</em>.</p><h3>Create the Middlewares - Logger, Dependency Injection</h3><p>Middleware in Dart Frog gives you the ability to execute code before or after a request is handled. You can modify an incoming request or an outgoing response, even inject a dependency to be used by the app.</p><p>We can chain multiple middlewares using the <em>use</em> API. For this app, we are going to use a built-in middleware <em>requestLogger</em> from the <a href="https://pub.dev/packages/dart_frog"><em>package:dart_frog</em></a> and it will automatically log all the requests to our server.</p><p>Also, this middleware is responsible for providing an instance of the <em>BooksDataSource</em> to all the routes so we have a single source of data for the lifetime of the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efa4c12caef4e2fe36801c1ed8337352/href">https://medium.com/media/efa4c12caef4e2fe36801c1ed8337352/href</a></iframe><h3>Create the /books route</h3><p>In the next step, delete the already existing route handler at <em>routes/index.dart</em> and create a new route handler for the <em>/books</em> endpoint by making <em>routes/books/index.dart</em>.</p><p>Now add the following content to the created file.</p><p>Note that, this endpoint will only handle the GET and POST methods, and for any other HTTP methods it will simply respond with <em>HttpStatus.methodNotAllowed</em> that represents the status code of 405.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c39be5a1c14fcbf2a0662289e0ae628/href">https://medium.com/media/8c39be5a1c14fcbf2a0662289e0ae628/href</a></iframe><h3>Complete the GET and POST methods</h3><p>The next step will be to complete the methods. We are going to use <em>context.read&lt;BooksDataSource&gt;()</em> to get access to the injected instance of the <em>BooksDataSource</em>.</p><p>In addition, during the POST method, we can access the provided JSON data via <em>context.request.json()</em> which returns a future map.</p><p>Also, note that we are using the <em>Response.json()</em> constructor to respond with <em>Content-Type: application/json</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c939dfd93aaf396be30076399447a1a8/href">https://medium.com/media/c939dfd93aaf396be30076399447a1a8/href</a></iframe><p>After hot reloading, we can now try to send requests to the <em>/books</em> route to get the expected results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7Q5JCgW4iUSri_7uvUclg.png" /><figcaption>HTTP Post Method - Create a new Book</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziVmreeX7Hqn4r6a5H0bsg.png" /><figcaption>HTTP Get Method - After adding two books</figcaption></figure><h3>Create the /books/[id] route</h3><p>Now the next step is to create a dynamic route handler that will be responsible for handling certain operations with a specific book record.</p><p>So, create a new route handler for the <em>/books/[id]</em> endpoint by making a file <em>routes/books/[id].dart</em>. This endpoint will only handle the GET, PUT, and DELETE methods, and for any other HTTP methods, it will simply respond with <em>HttpStatus.methodNotAllowed</em> that represents the status code of 405.</p><p>As we are handling dynamic routing with dynamic <em>id</em>, the <em>onRequest</em> method now has two parameters - one is <em>context</em> of type <em>RequestContext</em>, and the other one is <em>id</em> of type <em>String</em>.</p><p>The <em>id</em> segment is forwarded to the method call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aca607f9c1a9bafe312e232c4d266e98/href">https://medium.com/media/aca607f9c1a9bafe312e232c4d266e98/href</a></iframe><h3>Complete the GET, PUT and DELETE methods</h3><p>This step is similar to what we have done before while working with the index routing. Check out the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0ed47ebb2717793c68b9a439831115/href">https://medium.com/media/5b0ed47ebb2717793c68b9a439831115/href</a></iframe><p>Make sure to save all of your files, and the hot reload should take effect.</p><p>You are now ready to test the <em>/books/[id]</em> endpoint for fetching, updating, and deleting a specific book record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gPh3R-iwWgvZbygTELN3w.png" /><figcaption>HTTP Get Method - Fetch a book with the specified id</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujcQejikFlcGny6eZTbGLA.png" /><figcaption>HTTP Put Method - Update a book with the specified id</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0dlitplF5YXiz6DUSGBng.png" /><figcaption>HTTP Delete Method - Delete a book with the specified id</figcaption></figure><p><em>If you are interested in writing unit tests for the route handlers, middlewares, and the models and data source, then you can check them in the GitHub Repository.</em></p><p>The full source code for this application can be found here 👇</p><p><a href="https://github.com/thecodexhub/books-directory">GitHub - thecodexhub/books-directory: Books Directory app made with Dart Frog.</a></p><h3>Conclusion</h3><p>We now have a really good idea about the Dart Frog framework. Besides, we have also explored the usages of Middleware, Dependency Injection, Dynamic Routing, and how to test the endpoints using Postman.</p><p>Let’s celebrate then! 🎉</p><p>If you have any queries or suggestions or questions, dive into the comments sections. Alternatively, you can reach out to me using <a href="https://www.instagram.com/thecodexhub/"><strong><em>Instagram</em></strong></a>, <a href="https://twitter.com/thecodexhub"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/in/sandip-pramanik-56a4a51b2/"><strong><em>LinkedIn</em></strong></a>, or <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>Email</em></strong></a>.</p><p>Please remember to applaud if this article was insightful and taught you something unique. You know you can clap 50 times 🚀using that clap button. Give it a shot.😅</p><p>That’s it. Have a great day ahead!</p><p><a href="https://github.com/thecodexhub">thecodexhub - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcfca966c976" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/dart-frog-fast-minimalistic-backend-framework-for-dart-fcfca966c976">Dart Frog - Fast &amp; Minimalistic Backend Framework for Dart</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter and ObjectBox - High-Performance NoSQL Database]]></title>
            <link>https://towardsdev.com/flutter-and-objectbox-high-performance-nosql-database-e540b4ae91ee?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e540b4ae91ee</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[objectbox]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Sun, 28 Aug 2022 11:17:20 GMT</pubDate>
            <atom:updated>2022-09-08T15:12:35.441Z</atom:updated>
            <content:encoded><![CDATA[<p>Persisting data locally or remotely on the server is one of the fundamental requirements of any mobile application development process. Choosing a suitable database to work with, can sometimes be tricky.</p><p><a href="https://objectbox.io/"><strong>ObjectBox</strong></a> is a super-fast NoSQL ACID-compliant object persistence for cross-platform Flutter apps. An intuitive API, rich support for queries and relations, efficient data access, and minimal usage of CPU, memory, and battery make it an ideal choice for mobile devices.</p><p><em>“The NoSQL SQLite alternative for Mobile, IoT, and Embedded Devices.”</em></p><p>Additionally, the database can be kept optionally synchronized conveniently and effectively across multiple devices without any hassle from your side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNtx7V59GKUvzQQ2trsqDQ.png" /><figcaption>Benchmark of ObjectBox (source: <a href="https://pub.dev/packages/objectbox#flutter-database-performance-benchmarks">here</a>)</figcaption></figure><h3><em>What we are building</em></h3><p>We are going to build an <strong>Expense Tracker</strong> app that shows users their list of expenses. Through this app, we are going to explore entities, relations, reactive queries, ordering, and other functionalities.</p><p>You might ask if the above-said features are already explained beautifully in the official documentation of ObjectBox, then what is the requirement of this article?</p><p>Well, this article will not only help you with learning about ObjectBox, but also it will provide you with sufficient knowledge about how to use it in your next production application, how to maintain the codebase with proper architecture and state management techniques, and how to effectively isolate the presentation layer from the business logic layer.</p><p>Check out the below screenshots from the application we are going to build. Also, you might be curious to see how the app works, and for that, there is a <a href="https://www.instagram.com/reel/ChzQW6eIyWU/?utm_source=ig_web_copy_link"><strong><em>video link</em></strong></a> here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DARuLj013763pM4xJcon_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_IzykwoEder_TLgIVvaANQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PAaCKTYRqUCBCp8D-laYYg.png" /><figcaption>Screenshots from the application we are going to build</figcaption></figure><p>Feel free to check out the final repository anytime you got stuck.</p><p><a href="https://github.com/thecodexhub/flutter-objectbox-example">GitHub - thecodexhub/flutter-objectbox-example: Flutter project that shows how to work with ObjectBox - High Performance NoSQL Database.</a></p><h3>Table of Contents</h3><ul><li><a href="#9270"><em>Project Dependencies</em></a></li><li><a href="#d3d9"><em>Platform Specific Setup</em></a></li><li><a href="#de28"><em>Define the Entities - ExpenseType and Expense</em></a></li><li><a href="#d7d7"><em>Initialize Store with StoreRepository</em></a></li><li><a href="#956c"><em>Create ExpenseTypeRepository and ExpenseRepository</em></a></li><li><a href="#0e9c"><em>Create RepositoryProvider for the repositories</em></a></li><li><a href="#39b6"><em>Create the Forms for inputs</em></a></li><li><a href="#ca6b"><em>Models for Form Inputs</em></a></li><li><a href="#a863"><em>Blocs for Form inputs</em></a></li><li><a href="#3a72"><em>Create ExpenseTypeBloc - Fetch Stream, Delete</em></a></li><li><a href="#2396"><em>Create ExpenseType Page view and form</em></a></li><li><a href="#deef"><em>Create ExpenseBloc - Fetch Stream, Delete</em></a></li><li><a href="#3805"><em>Build the ExpensePage and ExpenseFormPage</em></a></li></ul><h3><em>Project Dependencies</em></h3><p>We shall start by replacing the pubspec.yaml file at the root of the project with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c294c951da6d96aed64f2f480223ac4/href">https://medium.com/media/0c294c951da6d96aed64f2f480223ac4/href</a></iframe><p>Well, that’s a large number of packages we are installing.</p><p>But you know, good practices are good practices. You can try replacing the versions of the packages with their latest versions. And the reason they are needed is already specified in the above gist.</p><h3><em>Platform Specific Setup</em></h3><p>Before we start writing our code, we need to do some initial setups to work with ObjectBox. Please follow the below link that will provide you with steps to do for the platforms you want to run the app.</p><p><a href="https://pub.dev/packages/objectbox#getting-started"><em>https://pub.dev/packages/objectbox#getting-started</em></a></p><p>For example, if you are planning to add the sync feature of the ObjectBox in your android app, you need to set the <em>minSdkVersion 21</em> in the <em>android/app/build.gradle</em> file. Here is how to do this.</p><p>Open the <em>local.properties</em> file that resides inside the <em>android</em> folder. And add the following line:</p><pre>flutter.minSdkVersion=21</pre><p>Then go to <em>android/app/build.gradle</em> file and check the <em>defaultConfig</em> section, update the <em>minSdkVersion</em> as following</p><pre>minSdkVersion localProperties.getProperty(‘flutter.minSdkVersion’).toInteger()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8X0o80aKMDTl95m78dYpyw.png" /></figure><h3><em>Define the Entities - ExpenseType and Expense</em></h3><p>Next, take a look at the entities. For this example, an expense type will consist of an identifier and name. Whereas, an expense entity will consist of an amount, note, and date when created.</p><p>In ObjectBox, <em>the persistable objects are called entities</em>. You can annotate classes with <strong>@Entity</strong> to help ObjectBox know which of them are entities. This will trigger ObjectBox to generate persistence code tailored for this class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e146c5738875bc743a5f875d6cec923/href">https://medium.com/media/1e146c5738875bc743a5f875d6cec923/href</a></iframe><p><em>Note: It’s completely up to you to define what a user needs to look like in the context of your requirement.</em></p><p>Additionally, there are more annotations available to configure your entity class and its properties like <strong><em>@Transient</em></strong>, <strong><em>@Index</em></strong>, <strong><em>@NameInDb</em></strong>, <strong><em>@Unique</em></strong>, <strong><em>@Property</em></strong>, etc. Check out the official documentation for more details.</p><p><a href="https://docs.objectbox.io/entity-annotations"><em>https://docs.objectbox.io/entity-annotations</em></a></p><p>After the annotations are placed in the right place, it is a good time to run the code generator using the <strong>build_runner</strong>. The boilerplate for the entities to be able to fetch from the database or persist in the database will be generated in the root of the <em>lib</em> folder. So let’s run the build_runner.</p><pre>flutter pub run build_runner watch — delete-conflicting-outputs</pre><p>You can see now that the <em>objectbox.g.dart</em> file has been generated and another file named <em>objectbox-model.json</em> has also been generated. This JSON file is going to be used by the ObjectBox sync to sync the data across multiple devices.</p><p><em>Now we are going to establish a relationship between the two entities.</em> Luckily, ObjectBox supports all kinds of relationships out of the box.</p><p>Relations will make it easy to access all the expenses made by a user. If you can remember, we have already discussed that one expense type can be associated with multiple expenses (to-many relationship), but one expense can be associated with only one expense type (to-one relationship)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16c658fc06b6a02fe9482e52f496c335/href">https://medium.com/media/16c658fc06b6a02fe9482e52f496c335/href</a></iframe><p><em>Note: The </em><strong><em>@Backlink</em></strong><em> annotation tells ObjectBox which </em><strong><em>ToOne</em></strong><em> relation to use to populate the list of expenses.</em></p><h3><em>Initialize Store with StoreRepository</em></h3><p>To access data from ObjectBox, we need to create a <strong>BoxStore</strong> object. And we can create the store using the model definition defined in the <em>objectbox.g.dart</em> file. Also, we can provide a directory to store the data.</p><p>You can create internal packages to better layer the application architecture and maintain clear boundaries, but for the sake of simplicity, you can follow along and create a new folder inside the lib directory and name it <em>repository</em>.</p><p>Then create a new file <em>store_repository</em> that will be responsible for abstracting the internal implementation details of how we initialize the store. Additionally, we will provide a getter to let other repository classes use the store object initialized in the <strong>StoreRepository</strong> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71cd36fd5d9b7b96a00fa881a3e8603e/href">https://medium.com/media/71cd36fd5d9b7b96a00fa881a3e8603e/href</a></iframe><h3><em>Create ExpenseTypeRepository and ExpenseRepository</em></h3><p>Let’s create an <strong>ExpenseTypeRepository</strong> to handle the add, get and delete functionality for the expense types. Similarly, we can create an <strong>ExpenseRepository</strong> for these same functionalities. But there is only one difference when adding an expense we need to set the expense type using the <strong><em>target</em></strong> keyword.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b9ab77aced561881f56a6465c7b2620/href">https://medium.com/media/7b9ab77aced561881f56a6465c7b2620/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01457c5674923dbf76b82de83ff75da1/href">https://medium.com/media/01457c5674923dbf76b82de83ff75da1/href</a></iframe><p>In a reactive framework like Flutter, it’s nearly always preferable to continuously monitor the data using a Stream that will emit a new event whenever the data in the database is modified, for example, when we add a new expense type or when we delete an expense.</p><p>Using ObjectBox we can do that easily with the in-built <em>watch()</em> method that returns <em>Stream&lt;Query&lt;T&gt;&gt;</em> which we can then map to get our expected result. The <em>watch()</em> method takes an optional parameter <em>triggerImmediately</em> (default is set to false), which if set to true, a single stream event will be sent immediately after subscribing.</p><p>Follow the below code that watches over the persisted data and the desired output is returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43a99537383562b0136f1956cf56f4a4/href">https://medium.com/media/43a99537383562b0136f1956cf56f4a4/href</a></iframe><p>In addition to specifying conditions, you can order the returned results using the order() method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b92d506b800dc4ebc10edf28ba949d10/href">https://medium.com/media/b92d506b800dc4ebc10edf28ba949d10/href</a></iframe><h3><em>Create RepositoryProvider for the repositories</em></h3><p>So now, as we have completed creating our repositories, we can inject them into our app using the <strong>RepositoryProvider</strong> so that we can work with only single instances of the repositories throughout the app.</p><p>The <em>main.dart</em> file can be replaced by the following code. We are simply setting up some global configuration along with initializing the ObjectBox store and calling <em>runApp</em> with an instance of the <em>App</em>.</p><p>Notice how we are injecting a single instance of the <strong>StoreRepository</strong> into the <em>App</em> and it is explicit constructor dependency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97841d4c9f5e1cf3fbec814ecbe3fc1e/href">https://medium.com/media/97841d4c9f5e1cf3fbec814ecbe3fc1e/href</a></iframe><p>Our app.dart will provide an instance of the <strong>StoreRepository</strong> to the application via the <strong>RepositoryProvider</strong> and also creates and provides the instances for the other repositories. After we are done, the app.dart file will look like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/605fcfd3eded1318c13d0e018820faa5/href">https://medium.com/media/605fcfd3eded1318c13d0e018820faa5/href</a></iframe><h3><em>Create the Forms for inputs</em></h3><p>From the screenshots of the application, we are going to build, you might have already figured out that we are going to have two separate forms - one for taking inputs to create expense types and another for creating expenses. Let’s finish setting up them quickly.</p><h3><em>Models for Form Inputs</em></h3><p>An <strong>Identifier</strong> and <strong>Name</strong> input model for <strong>ExpenseType</strong> and an <strong>Amount</strong> and <strong>Note</strong> input model for <strong>Expense</strong> are useful for encapsulating the validation logic and will be used in creating the user interactive forms.</p><p>All these input models are going to be created using the <a href="https://pub.dev/packages/formz"><strong><em>formz</em></strong></a> package that allows us to work with a validated value object rather than a primitive object type like <em>String</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b4595dd16d8134c596f38dd0215f99f/href">https://medium.com/media/6b4595dd16d8134c596f38dd0215f99f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/253e8c12ac9f14c84e218cee955da144/href">https://medium.com/media/253e8c12ac9f14c84e218cee955da144/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5737ca5408183606f575e857eb79143/href">https://medium.com/media/f5737ca5408183606f575e857eb79143/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f223f8b77b74801fd731eb251c55971/href">https://medium.com/media/1f223f8b77b74801fd731eb251c55971/href</a></iframe><h3><em>Blocs for Form inputs</em></h3><p>We will be creating two separate blocs - one for handling the <strong>ExpenseTypeForm</strong> and another for <strong>ExpenseForm</strong>.</p><p>Let’s start with <strong>ExpenseTypeFormBloc</strong>. This will be responsible for managing the <strong>ExpenseTypeFormState</strong> of the form. It exposes API for adding an expense type to the database, as well as gets notified when the identifier or the name is updated.</p><h4><strong>ExpenseTypeForm - </strong>State</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/140bb5b78d4e7ba75bcc5417992071ce/href">https://medium.com/media/140bb5b78d4e7ba75bcc5417992071ce/href</a></iframe><h4><strong>ExpenseTypeForm - </strong>Event</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dcc8ef979d115e01768f541da91df4e/href">https://medium.com/media/4dcc8ef979d115e01768f541da91df4e/href</a></iframe><h4><strong>ExpenseTypeForm - </strong>Bloc</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/985fd662e160a48843e30f4574d66e14/href">https://medium.com/media/985fd662e160a48843e30f4574d66e14/href</a></iframe><p>Next is the <strong>ExpenseFormBloc</strong>. This will be responsible for managing the ExpenseFormState of the form. Like the previous form bloc, this will also expose API for adding expenses to the database, as well as get notified when the amount or note or expense type gets changed.</p><p><em>The only difference is that we need an additional event to load up all the available expense types when the form is shown to the user.</em></p><h4><strong>ExpenseForm - </strong>State</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9968cbd9a275c3c92e40547ae215a8d6/href">https://medium.com/media/9968cbd9a275c3c92e40547ae215a8d6/href</a></iframe><h4><strong>ExpenseForm - </strong>Event</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8056165145aeac6350c5dbb5e775be94/href">https://medium.com/media/8056165145aeac6350c5dbb5e775be94/href</a></iframe><h4><strong>ExpenseForm - </strong>Bloc</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5f3a1e7117ef7ea4f42adaf30088ada/href">https://medium.com/media/a5f3a1e7117ef7ea4f42adaf30088ada/href</a></iframe><p><em>Let’s make a plan for the next steps before going further. The blocs that we have built just now are solely responsible only for managing the form data and submitting the forms. We need a separate set of blocs still to handle the fetch streams and other actions like delete.</em></p><h3><em>Create ExpenseTypeBloc - Fetch Stream, Delete</em></h3><p>Let’s start by creating the events. We are going to have an <strong>ExpenseTypeSubscriptionRequested</strong> event which is a startup event, in response to which the bloc will subscribe to the stream of expense types from the <strong>ExpenseTypeRepository</strong>. Another event <strong>ExpenseTypeDeleted</strong> will delete an expense type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a78c17547307176cf9ff671b1890e015/href">https://medium.com/media/a78c17547307176cf9ff671b1890e015/href</a></iframe><p>The <strong>ExpenseTypeState</strong> will keep track of the list of expense types, and the status.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1461bbd26a91fe16d6b47a1803244b2c/href">https://medium.com/media/1461bbd26a91fe16d6b47a1803244b2c/href</a></iframe><p>Now let’s create the Bloc. When <strong>ExpenseTypeSubscriptionRequested</strong> is added, the bloc starts by emitting a loading state. In response, the UI can render a loading widget. Next, we use</p><pre><em>emit.forEach&lt;List&lt;ExpenseType&gt;&gt;( … )</em></pre><p>which creates a subscription on the expense type stream from the <strong>ExpenseType</strong> repository.</p><p>And when the <strong>ExpenseTypeDeleted</strong> is added, it simply just calls the method from the repository. The emit is never called from within <strong>_onExpenseTypeDeleted</strong>. Instead, that notifies the repository and emits an updated list from the expense type streams.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76b31520f79129eb6e784caad68d9fe0/href">https://medium.com/media/76b31520f79129eb6e784caad68d9fe0/href</a></iframe><h3><em>Create ExpenseType Page view and form</em></h3><p>The <strong>ExpenseTypePage</strong> is responsible for creating and providing instances for <strong>ExpenseTypeFormBloc</strong> and <strong>ExpenseTypeBloc</strong> to the <strong>ExpenseTypeView</strong>.</p><p>It’s very important to keep the creation of blocs/cubits separate from where they are consumed. This will allow you to easily inject mock instances and test your view in isolation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d17a8d87f52804cd8798a95da965cc50/href">https://medium.com/media/d17a8d87f52804cd8798a95da965cc50/href</a></iframe><p>The <strong>ExpenseTypeView</strong> is responsible for rendering the form in response to the <strong>ExpenseTypeFormState</strong> and invokes events in response to the user interactions. Also, it renders the list of the <strong>ExpenseType</strong>s in response to the <strong>ExpenseFormState</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a993ca00d934f0370851f4edf6fa7d1/href">https://medium.com/media/6a993ca00d934f0370851f4edf6fa7d1/href</a></iframe><h3><em>Create ExpenseBloc - </em>Fetch Stream, Delete</h3><p>Similarly, we are going to have an <strong>ExpenseListRequested</strong> event which is a startup event, in response to which the bloc will subscribe to the stream of expenses from the <strong>ExpenseRepository</strong>.</p><p>Other events like <strong>ExpenseListSortByTimeRequested</strong>, <strong>ExpenseListSortByAmountRequested</strong>, <strong>ExpenseInLast7DaysRequested</strong> will subscribe to corresponding methods from the <strong>ExpenseRepository</strong>.</p><p>The <strong>ToggleExpenseSort</strong> will take care of changing the order type and adding the expected events to it. And the <strong>ExpenseDeleted</strong> will delete a particular expense from the database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a947fc6356e6ba4dfc398820d3c9da22/href">https://medium.com/media/a947fc6356e6ba4dfc398820d3c9da22/href</a></iframe><p>The <strong>ExpenseState</strong> will keep track of the list of expenses, the expense sort method, total expenses in the last 7 days, and the status.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06c8eb6be730225e68a8806acd94a3f0/href">https://medium.com/media/06c8eb6be730225e68a8806acd94a3f0/href</a></iframe><p>Now let’s create the Bloc. logically, it remains the same as <strong>ExpenseTypeBloc</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d77cf5d04f221f4394ad48ee23cd7126/href">https://medium.com/media/d77cf5d04f221f4394ad48ee23cd7126/href</a></iframe><h3><em>Build the ExpensePage and ExpenseFormPage</em></h3><p>The <strong>ExpensePage</strong> is responsible for creating and providing an instance for <strong>ExpenseBloc</strong> to the <strong>ExpenseView</strong>, which will then render the UI for different data available. Also, it renders the list of the <strong>Expense</strong>s in response to the <strong>ExpenseState</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5f7dacc666d9a2c90e28f969c1ddd60/href">https://medium.com/media/f5f7dacc666d9a2c90e28f969c1ddd60/href</a></iframe><p>On the other hand, The <strong>ExpenseFormPage</strong> is responsible for creating and providing an instance for <strong>ExpenseFormBloc</strong> to the <strong>ExpenseFormView</strong>. The <strong>ExpenseFormView</strong> is responsible for rendering the form in response to the <strong>ExpenseFormState</strong> and invokes events in response to the user interactions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d243bd7bfd56276527c47c5ea5eb774/href">https://medium.com/media/9d243bd7bfd56276527c47c5ea5eb774/href</a></iframe><p>Well, we are done now. If you face any challenges, you can always check out the source code.</p><p><a href="https://github.com/thecodexhub/flutter-objectbox-example">GitHub - thecodexhub/flutter-objectbox-example: Flutter project that shows how to work with ObjectBox - High Performance NoSQL Database.</a></p><h3>Conclusion</h3><p>If you have made it this far, congratulations!</p><p>If you have any queries or suggestions or questions, dive into the comments sections. Alternatively, you can reach out to me using <a href="https://www.instagram.com/thecodexhub/"><strong><em>Instagram</em></strong></a>, <a href="https://twitter.com/thecodexhub"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/in/sandip-pramanik-56a4a51b2/"><strong><em>LinkedIn</em></strong></a>, or <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>Email</em></strong></a>.</p><p>Please remember to applaud if this article was helpful and taught you something new. You know you can clap 50 times 🚀using that clap button. Give it a shot.😅</p><p>That’s it. Hope it helps!</p><p><a href="https://github.com/thecodexhub">thecodexhub - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e540b4ae91ee" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/flutter-and-objectbox-high-performance-nosql-database-e540b4ae91ee">Flutter and ObjectBox - High-Performance NoSQL Database</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slivers in Flutter - Efficient and Fancy Scrolling Experience]]></title>
            <link>https://towardsdev.com/slivers-in-flutter-efficient-and-fancy-scrolling-experience-9a3f5b370666?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a3f5b370666</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[slivers]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 09:32:59 GMT</pubDate>
            <atom:updated>2022-08-19T07:11:41.298Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn one of the scariest topics in Flutter - what is sliver and how to make use of it to build an elegant scroll view</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vJHfSGx7nZrGsz9g" /><figcaption>Photo by <a href="https://unsplash.com/@nathanareboucas?utm_source=medium&amp;utm_medium=referral">Nathana Rebouças</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>Widgets</em></strong> are the foundation of Flutter’s layout system. Almost everything in Flutter is a widget, including layout models. Widgets are what you see in a Flutter app as images, icons, and text. Things you can’t see, such as the rows, columns, and grids that arrange, constrain, and align the visible widgets, are also widgets.</p><p>The <a href="https://api.flutter.dev/flutter/rendering/RenderObject-class.html"><strong>RenderObject</strong></a> class is the core of the rendering library and it handles the visual elements tree and specifies the layout, painting, and composting procedures. RenderObject doesn’t have any specific layout protocol, and it also doesn’t define a child model. The implementers of RenderObject class (such as <a href="https://api.flutter.dev/flutter/rendering/RenderBox-class.html"><strong>RenderBox</strong></a>, <a href="https://api.flutter.dev/flutter/rendering/RenderSliver-class.html"><strong>RenderSliver</strong></a>, <a href="https://api.flutter.dev/flutter/rendering/RenderAbstractViewport-class.html"><strong>RenderAbstractViewport</strong></a>, and <a href="https://api.flutter.dev/flutter/rendering/RenderView-class.html"><strong>RenderView</strong></a>) introduce layout systems and child models.</p><p><em>Most of the RenderObjects are RenderBox.</em></p><p>The <strong>RenderBox</strong> has its cartesian coordinate system and box constraints that determine the minimum and maximum value of the height and width of its child. These values are then used to find out the size of the child.</p><p>Common examples of RenderBox are Container, SizedBox, etc. They follow the RenderBox protocol to describe and paint the layout model based on the Cartesian space and box constraints.</p><h3><em>What are Slivers?</em></h3><p>While <strong>RenderBox</strong> is ideal for rendering objects in cartesian coordinates, they are not a good fit for scrolling widgets. For scrolling, there is Sliver protocol. The render objects that implement scroll effects in viewports use <strong>RenderSliver</strong> as their base class.</p><p><strong>Sliver</strong> is a segment of the viewport’s content that is laid out to cover up the viewport. Slivers participate in sliver protocol.</p><p>In the case of box protocol, the RenderBox gets the box constraints and determines the child&#39;s size. Similarly, in sliver protocol, during the layout mechanism, the sliver gets a <a href="https://api.flutter.dev/flutter/rendering/SliverConstraints-class.html"><strong>SliverConstraints</strong></a> and calculates the corresponding <a href="https://api.flutter.dev/flutter/rendering/SliverGeometry-class.html"><strong>SliverGeometry</strong></a> that tells where to fit in the sliver in the viewport.</p><h3><em>Need for Slivers: Advantages</em></h3><p>Under the hood, slivers are used to implement all of the scrollable views you use, including ListView and GridView. Slivers can be compared to a lower-level interface that offers more precise control over the implementation of scrollable areas.</p><p><a href="https://api.flutter.dev/flutter/rendering/RenderSliver-class.html"><strong>RenderSliver</strong></a> lets you render child widgets lazily or render only the visible segment of the screen. Additionally, RenderSliver provides a better experience when you need to scroll a list of items and a grid of items all together as a single unit or create a collapsible header. It makes the overall scrolling effect of large lists effective and efficient.</p><h3><em>How to work with Slivers</em></h3><p>To create a scroll view with custom scroll effects using slivers, we need to use the <a href="https://api.flutter.dev/flutter/widgets/CustomScrollView-class.html"><strong>CustomScrollView</strong></a> widget. Slivers can be directly supplied to a CustomScrollView to produce a variety of scrolling effects, including lists, grids, and collapsible headers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5213695e663f231e2ab65c3571bc57bb/href">https://medium.com/media/5213695e663f231e2ab65c3571bc57bb/href</a></iframe><h3><em>Scrollable app bar: SliverAppBar</em></h3><p><a href="https://api.flutter.dev/flutter/material/SliverAppBar-class.html"><strong>SliverAppBar</strong></a> is a material-designed app bar that can be integrated with CustomScrollView. Typically, <strong>SliverAppBar</strong>s are used as the first child of the CustomScrollView that integrates the app bar with the scroll view so that the app bar can scroll, and change heights depending upon the scroll offset.</p><p>If the <a href="https://api.flutter.dev/flutter/material/SliverAppBar/flexibleSpace.html"><strong>flexibleSpace</strong></a> is defined, it is rendered behind the toolbar and the bottom widget. And its height can be determined from the specified <strong>expandedHeight</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4747868264603789177fe8aa46c4c95/href">https://medium.com/media/a4747868264603789177fe8aa46c4c95/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfxFkXMc-g5xLpa1FZ_SBg.gif" /></figure><h3><em>Pinned, Floating, and Snap app bar</em></h3><p>Also, there are some other cool properties of the SliverAppBar.</p><p>If the <strong>pinned</strong> is set to <em>true</em>, the app bar gets pinned and remains visible at the top of the scroll view.</p><p>If the <strong>floating</strong> is set to <em>true</em>, the app bar gets visible as soon as the user starts scrolling backward. Otherwise, if floating is false, the user has to go to the top to reveal the app bar.</p><p>And if the <strong>snap</strong> is set to <em>true</em>, the app bar will be fully expanded when you scroll back. Remember, the snap can only be set to true if the floating is true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49b6bc5ee294d2e496bc61a5c34b9681/href">https://medium.com/media/49b6bc5ee294d2e496bc61a5c34b9681/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcjMj-6LC4Redrquxijd5Q.gif" /><figcaption>When pinned is true and floating, snap are false</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqyKbxJmzgXvc8sw0wk6IA.gif" /><figcaption>When floating is true but pinned and snap are false</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QNtemXG8gjYMUPJdfwbzQ.gif" /><figcaption>When floating and snap are true, and pinned is false</figcaption></figure><h3><em>All about SliverList</em></h3><p>The <a href="https://api.flutter.dev/flutter/widgets/SliverList-class.html"><strong>SliverList</strong></a> widget is a sliver that renders multiple children in a linear way along the main axis. While rendering the list, the elements, states, and the rendering of the already visible render objects in the viewport will be laid out lazily based on an already existing widget (such as <a href="https://api.flutter.dev/flutter/widgets/SliverChildListDelegate-class.html"><strong>SliverChildListDelegate</strong></a>) or lazily-provided one (such as <a href="https://api.flutter.dev/flutter/widgets/SliverChildBuilderDelegate-class.html"><strong>SliverChildBuilderDelegate</strong></a>).</p><p>Alternatively, we can also use the <a href="https://api.flutter.dev/flutter/widgets/SliverFixedExtentList-class.html"><strong>SliverFixedExtentList</strong></a>, which is more efficient for children with the same extent in the main axis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e8314d31e17c9ecff169391e861158b/href">https://medium.com/media/1e8314d31e17c9ecff169391e861158b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asmWhpWr8sG7RMM02V8nqg.gif" /><figcaption>SliverList with SliverAppBar having all pinned, floating and snap set to true</figcaption></figure><h3><em>Grid layout with SliverGrid</em></h3><p>The <a href="https://api.flutter.dev/flutter/widgets/SliverGrid-class.html"><strong>SliverGrid</strong></a> widget lays out its children in an arbitrary two-dimensional arrangement based on the <a href="https://api.flutter.dev/flutter/widgets/SliverGrid/gridDelegate.html"><strong>gridDelegate</strong></a>. Similarly, as SliverList, while rendering, the render objects in the viewport will be laid out either by specifying the children list (using <a href="https://api.flutter.dev/flutter/widgets/SliverChildListDelegate-class.html"><strong>SliverChildListDelegate</strong></a>) or by creating them lazily (using <a href="https://api.flutter.dev/flutter/widgets/SliverChildBuilderDelegate-class.html"><strong>SliverChildBuilderDelegate</strong></a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f6e4f2d8a04896e8b1e3d898db9db2d/href">https://medium.com/media/1f6e4f2d8a04896e8b1e3d898db9db2d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gJ3O3-Ah0WQMh4RTpSJzA.gif" /><figcaption>SliverGrid along with SliverList</figcaption></figure><h3><em>Sliver with single widget: SliverToBoxAdapter</em></h3><p>The <a href="https://api.flutter.dev/flutter/widgets/SliverToBoxAdapter-class.html"><strong>SliverToBoxAdapter</strong></a> is a sliver widget that holds one single box widget.</p><p>Slivers are special purpose widgets that can be coupled with a CustomScrollView to produce a fancy scrolling experience. A <strong>SliverToBoxAdapter</strong> is a straightforward sliver that builds a link to a common box-based widget.</p><p>Consider using <a href="https://api.flutter.dev/flutter/widgets/SliverList-class.html"><strong>SliverList</strong></a>, <a href="https://api.flutter.dev/flutter/widgets/SliverFixedExtentList-class.html"><strong>SliverFixedExtentList</strong></a>, or <a href="https://api.flutter.dev/flutter/widgets/SliverGrid-class.html"><strong>SliverGrid</strong></a>, which are more efficient because they instantiate only those children that are visible through the scroll view’s viewport, rather than multiple SliverToBoxAdapter widgets to display multiple box widgets in a CustomScrollView.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9457605055b9655996ab206b76547dce/href">https://medium.com/media/9457605055b9655996ab206b76547dce/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6XcLALoVNvBC1e50P1iLA.gif" /><figcaption>SliverToBoxAdapter with a single box object — Container</figcaption></figure><h3><em>SliverFillRemaining: Fill the remaining viewport</em></h3><p>A sliver that occupies the remaining space in the viewport with a single box child is the <a href="https://api.flutter.dev/flutter/widgets/SliverFillRemaining-class.html"><strong>SliverFillRemaining</strong></a> widget. The child will be sized to fill the cross-axis extent but the size in the main axis will be determined conditionally using the <a href="https://api.flutter.dev/flutter/widgets/SliverFillRemaining/hasScrollBody.html"><strong>hasScrollBody</strong></a> property.</p><p>The <strong>hasScrollBody</strong> indicates whether the child of the SliverFillRemaining sliver is scrollable. If the value is <em>true</em> (also default is set to <em>true</em>), the child will be sized to fill the maximum main axis extent. And if the property is set to <em>false</em>, the child’s size will be taken into account to determine the extent to which it should fill the space.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fee890ba8513b99b33cf1ec05f5fde82/href">https://medium.com/media/fee890ba8513b99b33cf1ec05f5fde82/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twFa0mjD2zSWo9EM0Vom9Q.gif" /><figcaption>SliverFillRemaining widget</figcaption></figure><h3><em>Custom reusable headers with SliverPersistentHeader</em></h3><p><a href="https://api.flutter.dev/flutter/material/SliverAppBar-class.html"><strong>SliverAppBar</strong></a>, under the hood, is a <a href="https://api.flutter.dev/flutter/widgets/SliverPersistentHeader-class.html"><strong>SliverPersistentHeader</strong></a> widget. While the SliverAppBar is customizable, sometimes you’ll need more customization and you’ll find most of the properties of the SliverAppBar in the SliverPersistentHeader along with some more customization options.</p><p>We’ll use the <strong>SliverPersistentHeader</strong> to make a sophisticated, persistent subheader that expands when you scroll down but maintains a minimum height when you scroll up.</p><p>SliverPersistentHeader requires a delegate class that extends the abstract class <a href="https://api.flutter.dev/flutter/widgets/SliverPersistentHeaderDelegate-class.html"><strong>SliverPersistentHeaderDelegate</strong></a>. You should override the <a href="https://api.flutter.dev/flutter/widgets/SliverPersistentHeaderDelegate/shouldRebuild.html"><strong>shouldRebuild</strong></a> to rebuild whenever one of these three properties changes - minHeight, maxHeight, and child.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6f8395da7459af7b78d4bf1cc179c53/href">https://medium.com/media/a6f8395da7459af7b78d4bf1cc179c53/href</a></iframe><p>And now as we have our custom SliverPersistentHeaderDelegate, we can complete making our <strong>SliverPersistentHeader</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b723b3e47c35bd056caca162d55b022/href">https://medium.com/media/8b723b3e47c35bd056caca162d55b022/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RoSqK-T1rxOEx4bO2h0Hg.gif" /><figcaption>SliverPersistentHeader widget</figcaption></figure><h3><em>Complete project with source code</em></h3><p>Check out the complete source code for this application via the following link.</p><p><a href="https://github.com/thecodexhub/flutter-slivers-example">GitHub - thecodexhub/flutter-slivers-example: Slivers in Flutter - Efficient and Fancy Scrolling Experience. Learn one of the scariest topics in Flutter - what is sliver and how to make use of it to make an elegant scroll view.</a></p><h3><em>Conclusion</em></h3><p>In this article, we have covered how to use slivers to make the scrolling experience much more elegant and sophisticated in Flutter. The background of the scrolling widgets, render objects, box protocol, and sliver protocol have also been covered in this article.</p><p>We have explored some of the in-built sliver widgets including <em>SliverAppBar</em>, <em>SliverList</em>, <em>SliverGrid</em>, <em>SliverToBoxAdapter</em>, and <em>SliverFillRemaining </em>to create fancy looking UI. Also, we have looked into <em>SliverPersistentHeader</em> to create a custom collapsible subheader.</p><p>If you have any queries or suggestions or questions, dive into the comments sections. Alternatively, you can reach out to me using <a href="https://www.instagram.com/thecodexhub/"><strong><em>Instagram</em></strong></a>, <a href="https://twitter.com/thecodexhub"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/in/sandip-pramanik-56a4a51b2/"><strong><em>LinkedIn</em></strong></a>, or <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>Email</em></strong></a>.</p><p>Please remember to applaud if this article was helpful and taught you something new. You know you can clap 50 times 🚀using that clap button. Give it a shot.😅</p><p>That’s it. Hope it helps!</p><p><a href="https://github.com/thecodexhub">thecodexhub - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3f5b370666" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/slivers-in-flutter-efficient-and-fancy-scrolling-experience-9a3f5b370666">Slivers in Flutter - Efficient and Fancy Scrolling Experience</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigator 2.0 with GoRouter]]></title>
            <link>https://towardsdev.com/flutter-navigator-2-0-with-gorouter-fb2dd998e40e?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb2dd998e40e</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[go-router]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 15:42:52 GMT</pubDate>
            <atom:updated>2022-08-23T12:17:35.600Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn about the declarative routing mechanism in Flutter using the go_router package</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*74OX7kgt-Jg-Noyu" /><figcaption>Photo by <a href="https://unsplash.com/@diegojimenez?utm_source=medium&amp;utm_medium=referral">Diego Jimenez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Navigation is a core concept in app development. Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app.</p><h3>Table of Contents</h3><ul><li><a href="#cb87"><em>What is GoRouter?</em></a></li><li><a href="#bb9b"><em>Now, What is Navigator 2.0?</em></a></li><li><a href="#a551"><em>Advantages of the Navigator 2.0</em></a></li><li><a href="#cae0"><em>How to implement the new Navigator technique?</em></a></li><li><a href="#050c"><em>Getting Started with GoRouter</em></a></li><li><a href="#2f4d"><em>Get the Dependencies</em></a></li><li><a href="#78c8"><em>Repository and Screens</em></a></li><li><a href="#17b5"><em>Initial setup for GoRouter</em></a></li><li><a href="#86c0"><em>Error handling</em></a></li><li><a href="#05a2"><em>Navigation</em></a></li><li><a href="#8798"><em>Sub routes</em></a></li><li><a href="#e065"><em>Parameters and Query Parameters</em></a></li><li><a href="#338e"><em>Web history and neglect tracking</em></a></li></ul><h3><em>What is GoRouter?</em></h3><p><a href="https://gorouter.dev/"><strong>GoRouter</strong></a> is a declarative router for Flutter apps based on Navigation 2.0 to reduce complexity, regardless of the platform the app is running (mobile, web, or desktop), handle deep and dynamic linking, and data-driven routes while still providing an easy-to-use developer experience.</p><h3><em>Now, What is Navigator 2.0?</em></h3><p>The <strong><em>Navigator</em></strong> widget in Flutter is an <em>imperative</em> routing mechanism (Navigator 1.0), and Navigator 2.0 is the standard reference to <em>declarative</em> navigation and does not replace Navigator 1.0, as they can be used together. Navigator 2.0 offers a new declarative API design, Pages, for the existing Navigator widget. It also introduces a new <strong><em>Router</em></strong> widget.</p><ul><li><em>Ah, now what is imperative and declarative?</em></li><li><em>Why bother about Navigator 2.0 when we already have a routing mechanism that works well and is easy?</em></li></ul><p>This time, let’s start from the very depth. 📈</p><p><strong><em>Imperative Programming</em></strong> is a programming paradigm that describes how a program will be executed. Developers are more concerned with the process of obtaining a solution step by step.</p><p>Whereas, <strong><em>Declarative Programming</em></strong> is a programming paradigm that expresses the logic of a computation without describing its control flow.</p><p>For example, <em>Imperative Programming</em> is like asking your friend how to solve a problem step by step. And <em>Declarative Programming</em> is like asking your friend to solve that problem, here you don’t care how he fixes the problem, you focus on the end result.</p><p>In Flutter, small applications are typically well served by simply using the <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html"><strong><em>Navigator</em></strong></a> API via the MaterialApp constructor’s <a href="https://api.flutter.dev/flutter/material/MaterialApp/routes.html"><strong><em>MaterialApp.routes</em></strong></a> property.</p><p>But, more complex applications are generally served better by the <a href="https://api.flutter.dev/flutter/widgets/Router-class.html"><strong><em>Router</em></strong></a> API, which is accessible via the <a href="https://api.flutter.dev/flutter/material/MaterialApp/MaterialApp.router.html"><strong><em>MaterialApp.router</em></strong></a> constructor. This takes a little more work upfront to describe how to parse deep links for your application and how to map the application state to the set of active pages, but it is more expressive in the long run.</p><h3><em>Advantages of the Navigator 2.0</em></h3><p>In Navigator 1.0, you can only add a page to the top of the navigation stack and remove the topmost route. The declarative mechanism, Navigator 2.0, on the other hand, gives you complete control over the navigation stack.</p><p>When the Web platform is targeted, parsing and restoring URLs add significant value to app navigation. The new API includes a component in charge of parsing URLs entered in the Web browser’s address bar and restoring URLs in the address bar as the application state changes.</p><h3><em>How to implement the new Navigator technique?</em></h3><p>Navigator 2.0 introduces <strong><em>Pages</em></strong>, a new declarative API design for the existing <strong><em>Navigator</em></strong> widget. It also adds a new <em>Router</em> widget. Customized <strong>RouterDelegate</strong> and <strong>RouteInformationParser</strong> classes are required for this new routing system. Both of these classes require a significant amount of effort to implement and will still leave you puzzled.</p><p>Some developers come up with their packages to make things a little bit easier and are made on top of the new declarative navigation mechanism - <a href="https://pub.dev/packages/auto_route"><strong><em>AutoRoute</em></strong></a>, <a href="https://pub.dev/packages/beamer"><strong><em>Beamer</em></strong></a>, <a href="https://pub.dev/packages/vrouter"><strong><em>VRouter</em></strong></a>. All of these three have their strengths and weaknesses. For example, <em>AutoRoute</em> generally requires code generation. <em>Beamer</em> appeared exciting, but it’s a little bit ambiguous. Flutter developers were puzzled by <em>VRouter</em>’s similarly named APIs, which were used in different contexts.</p><p>There comes the <a href="https://pub.dev/packages/go_router"><strong><em>go_router</em></strong></a> package with its intuitive and easy-to-use navigation approach. In this tutorial, we are going to see how to implement Navigator 2.0 using <strong><em>GoRouter</em></strong> and how it provides much more granular control for your app’s navigation.</p><h3><em>Getting Started with GoRouter</em></h3><p>In this tutorial, we are going to build a very simple application using <strong>GoRouter</strong>. The app will have three screens - <strong><em>LandingScreen </em></strong>which will be the initial screen, <strong><em>ColorExploreScreen</em></strong> which grids out a number of colored containers, and <strong><em>ColorShadeScreen </em></strong>which is responsible to list out different shades of a specific color based on an <em>alpha</em> value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*P1G5Yatug4k-A4fB2yOoqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*be928SRbzYbEmaUguj60UQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*TRQJjbJC-FcobmwrxXuaSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*QhsJE7mhUvyDIPq7TmbPjw.png" /></figure><h3><em>Get the Dependencies</em></h3><p>In this project we require two dependencies:</p><ol><li><a href="https://pub.dev/packages/flutter_bloc"><strong><em>flutter_bloc</em></strong></a>: To work with a repository class. For this tutorial, making a repository class and creating a provider to manage it, wasn’t necessarily required. We could have done it in a different manner too. But good practices are good practices. Also, this makes our work a little bit easier, so we’ll make use of it.</li><li><a href="https://pub.dev/packages/go_router"><strong><em>go_router</em></strong></a>: To reduce the complexity of the declarative routing mechanism.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b80b89b67827ba8ed6759593398a261/href">https://medium.com/media/6b80b89b67827ba8ed6759593398a261/href</a></iframe><h3><em>Repository and Screens</em></h3><p>Let’s create a repository class to hold a number of different colors, and also declare some helper methods. Check out the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/023a46c5cc83124ca144fc74385a1fb1/href">https://medium.com/media/023a46c5cc83124ca144fc74385a1fb1/href</a></iframe><p>And create an instance of the repository using <strong><em>RepositoryProvider</em></strong>, as an ancestor widget of the <strong><em>MaterialApp</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a87eee4d644ba5faeeacb9b82bc4eb7f/href">https://medium.com/media/a87eee4d644ba5faeeacb9b82bc4eb7f/href</a></iframe><p>There are three screens. Let’s discuss their routes or paths.</p><p><strong>/</strong> → will represent the <strong><em>LandingScreen()</em></strong> widget.</p><p><strong>/colors</strong> → will represent the <strong><em>ColorExploreScreen()</em></strong> widget.</p><p><strong>/colors/:index</strong> → will represent the <strong><em>ColorShadeScreen(index: index)</em></strong> widget with a specific color at <strong><em>index</em></strong>.</p><p>The last route may also contain some query parameters</p><p><strong>/colors/:idx?alpha={alpha}</strong> → will represent the <strong><em>ColorShadeScreen(index: index, alpha: alpha)</em></strong> widget.</p><p>Now our job is to connect everything in such a way that whenever some interaction happens we call the necessary routes with the necessary parameters. And these parameters must be extracted by the widgets to show the proper result.</p><h3><em>Initial setup for GoRouter</em></h3><p>The <a href="https://pub.dev/packages/go_router"><strong><em>go_router</em></strong></a> package has two main classes that you need to use - <strong><em>GoRouter</em></strong> and <strong><em>GoRoute</em></strong>. Creating a <strong><em>GoRouter</em></strong> constructor will give you a <strong><em>RouterDelegate</em></strong>, <strong><em>RouteInformationParser,</em></strong> and a <strong><em>RouteInformationProvider</em></strong>.</p><p>For routes, <strong><em>GoRouter</em></strong> uses a <strong><em>GoRoute</em></strong> that contains a <strong><em>path</em></strong> responsible for determining the URL, a <strong><em>builder</em></strong> that returns a page and a <strong><em>redirect</em></strong> handler that redirects to another route.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e267826cf0b40bdde1276b929c580fb8/href">https://medium.com/media/e267826cf0b40bdde1276b929c580fb8/href</a></iframe><h3><em>Error handling</em></h3><p>GoRouter by default includes default error screens for both MaterialApp and CupertinoApp in addition to a default error screen if you’re not using either. You can set the <strong><em>errorBuilder</em></strong> parameter of the GoRouter to replace the default error screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e792cef234f532ecf7393b45baf6efc2/href">https://medium.com/media/e792cef234f532ecf7393b45baf6efc2/href</a></iframe><h3><em>Navigation</em></h3><p>In order to navigate from one screen to another, there are a few ways of doing it. We can navigate using GoRouter or using the Dart extension method or using the Link widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1735944fe200ab7339f81f3eb9591840/href">https://medium.com/media/1735944fe200ab7339f81f3eb9591840/href</a></iframe><h3><em>Sub routes</em></h3><p>Every top-level route will generate a single-page navigation stack in GoRouter. And sub-routes are used to create a navigation stack. Now check the below snippet carefully.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daf3a21ae5ea171ac1a0b401cca86474/href">https://medium.com/media/daf3a21ae5ea171ac1a0b401cca86474/href</a></iframe><p>In the first case, <strong><em>/</em></strong> and <strong><em>/colors</em></strong> both are top-level routes. Whereas, in the second case, <strong><em>/colors</em></strong> is a sub-route of <strong><em>/</em></strong>. And there are two ways we can navigate to the <strong><em>/colors </em></strong>page from the home page. Either using <strong>context.go(&#39;/colors&#39;) </strong>or <strong>context.push(&#39;/colors&#39;)</strong>. So what is the difference between <strong>go </strong>and <strong>push</strong>?</p><p>Let’s take another example to understand the difference carefully.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f29ab971ecc6c811f22fab889b116dfa/href">https://medium.com/media/f29ab971ecc6c811f22fab889b116dfa/href</a></iframe><p>See the <strong><em>/profile</em></strong> and <strong><em>/dashboard</em></strong> are the sub-routes of <strong><em>/user</em></strong> route. So if you are on the <strong><em>/user</em></strong> route it has started creating a navigation stack. When you navigate from <strong><em>/user</em></strong> to <strong><em>/profile</em></strong> route using <strong>context.go(‘/profile’)</strong> or <strong>context.push(‘/profile’)</strong>, the profile route will be added on top of the users route as the profile is a sub-route of the user route. A similar thing happens when you navigate from <strong><em>/user</em></strong> to <strong><em>/dashboard</em></strong> route.</p><p>Go and Push works differently when you try to navigate from <strong><em>/profile</em></strong> to <strong><em>/dashboard</em></strong> route or vice versa. Let&#39;s say you are on the <strong><em>/profile</em></strong> route. So the navigation stack is made up with <strong><em>/user</em></strong> and <strong><em>/profile</em></strong>. Now if you do <strong>context.go(‘/dashboard’)</strong>, it will jump to the target route <strong><em>/dashboard</em></strong> by removing the <strong><em>/profile</em></strong> route as <strong><em>/dashboard</em></strong> is not a sub-route of <strong><em>/profile</em></strong>.</p><p>But if you do <strong>context.push(‘/dashboard’)</strong> from the <strong><em>/profile</em></strong> route, it will push the target route into the already available navigation stack.</p><h3><em>Parameters and Query Parameters</em></h3><p>Both these terms are closely related but they are not the same at all, <strong><em>Parameters</em></strong> are set for the route, <strong><em>Query Parameters</em></strong> are values resembling variable assignment that provide extra information on what is being required for the route and it will always start with a ‘<strong><em>?</em></strong>’ on the URL, inherently they are both string values.</p><p>For example, from the route: <strong><em>creatures/:name</em></strong></p><ul><li>if we were to make a request to <strong><em>/creatures/alces</em></strong>, then <strong><em>alces</em></strong> is the <strong><em>name</em></strong> parameter.</li><li>if we were to make a request to <strong><em>/creatures/alces?familyName=Moose</em></strong>, then <strong><em>alces</em></strong> is the <strong><em>name</em></strong> parameter and <strong><em>Moose</em></strong> is the <strong><em>familyName</em></strong> query parameter.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43192748ded9972982ae3c76b1b24e04/href">https://medium.com/media/43192748ded9972982ae3c76b1b24e04/href</a></iframe><h3><em>Web history and neglect tracking</em></h3><p>Every top-level route will create a navigation stack of one page. Sub-routes create an entire stack of pages so that it becomes easy to navigate to the previous or to the next page using arrow buttons in the browser. But sometimes, you may want to neglect to stack up pages.</p><p>For example, every time you change the alpha value it creates another page in our project. So if you want to go back to the explore screen via the back button, it will go through a number of screens. So let’s neglect to stack up pages when altering the alpha values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd3d393e7727973f0415b436156f23ef/href">https://medium.com/media/fd3d393e7727973f0415b436156f23ef/href</a></iframe><p>If you want to know more and more in detail, check out the official documentation here at <a href="https://gorouter.dev/"><strong><em>gorouter.dev</em></strong></a>.</p><p>The full source code for this application can be found here 👇</p><p><a href="https://github.com/thecodexhub/flutter-go-router-example">GitHub - thecodexhub/flutter-go-router-example: Flutter GoRouter Example</a></p><h3>Conclusion</h3><p>We now have a really good idea about Navigator 2.0 and how to implement using the <a href="https://pub.dev/packages/go_router"><strong><em>go_router</em></strong></a> package. We have also experimented with its declarative routing, navigations, parameters, query parameters, and sub-routing.</p><p>Let’s celebrate then! 🎉</p><p>If you have any queries or suggestions or questions, dive into the comments sections. Alternatively, you can reach out to me using <a href="https://www.instagram.com/thecodexhub/"><strong><em>Instagram</em></strong></a>, <a href="https://twitter.com/thecodexhub"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/in/sandip-pramanik-56a4a51b2/"><strong><em>LinkedIn</em></strong></a>, or <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>Email</em></strong></a>.</p><p>Please remember to applaud if this article was insightful and taught you something amazing. You know you can clap 50 times 🚀using that clap button. Give it a shot.😅</p><p>That’s it. Have a great day ahead!</p><p><a href="https://github.com/thecodexhub">thecodexhub - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb2dd998e40e" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/flutter-navigator-2-0-with-gorouter-fb2dd998e40e">Flutter Navigator 2.0 with GoRouter</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TextInputFormatter in Flutter - Format User’s Input on-the-fly]]></title>
            <link>https://towardsdev.com/textinputformatter-in-flutter-format-users-input-on-the-fly-71510af8a44c?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/71510af8a44c</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Sat, 25 Jun 2022 20:18:00 GMT</pubDate>
            <atom:updated>2022-08-18T09:00:50.776Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to format user input in real-time for a text field, minimize errors and improve user experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5iRJwKecS8Slsaab" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, you will discover how to format user input in real-time for a text field. When a user enters text into an input field, the value is automatically formatted to reflect the changes, including the addition of dashes and punctuation, the removal of unnecessary characters, the trimming of spaces, and the changing of word case.</p><p>This method can tremendously help users while filling out forms. It streamlines the procedure, reduces mistakes, provides feedback, and generally enhances the user experience.</p><p>We’ll look at a variety of examples, starting with formatter for username, phone number, credit card number, and date of birth. Also, we are going to deep dive into the TextInputFormatter, and understand the logic between each line of code to make this learning more convenient and intuitive.</p><h3><em>What is TextInputFormatter?</em></h3><p>Flutter provides an abstract class, <strong><em>TextInputFormatter</em></strong>, responsible for validating as-you-type and formatting the text being edited. It can be optionally injected into a <em>TextField</em> or <em>TextFormField</em>.</p><p>Developers can specify the behavior of a <em>TextField</em> or a <em>TextFormField</em> by passing a list of implementation classes of <strong><em>TextInputFormatter</em></strong> to the <strong><em>inputFormatters</em></strong> argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*IhCzkSpq7wQMs5PSj_ZwMw.png" /><figcaption>‘inputFormatters’ in TextField</figcaption></figure><h3><em>Built-in TextInputFormatter Implementations</em></h3><p>Flutter framework offers us two <strong><em>TextInputFormatter</em></strong> implementations:</p><blockquote><strong>FilteringTextInputFormatter<em> - </em></strong>A TextInputFormatter that allows or prevents the insertion of characters matching a particular pattern.</blockquote><blockquote><strong>LengthLimitingTextInputFormatter<em> - </em></strong>A TextInputFormatter that prevents the insertion of more characters than allowed.</blockquote><h3><em>About FilteringTextInputFormatter</em></h3><p>The <strong><em>FilteringTextInputFormatter</em></strong> is a built-in implementation of the <strong><em>TextInputFormatter</em></strong> class. It has three constructors for filtering out the user’s text input on the fly.</p><h4><strong><em>1. FilteringTextInputFormatter()</em></strong></h4><p>This is a parameterized constructor that prevents the insertion of characters based on the <strong><em>filterPattern</em></strong> positional parameter. The <strong><em>filterPattern</em></strong> is a <strong><em>Pattern</em></strong> to match or replace incoming characters.</p><p>This constructor has a required named parameter - <strong><em>allow</em></strong> of type boolean. If <strong><em>allow</em></strong> is false, then the filter pattern is a deny filter, otherwise, an allow filter.</p><p>Also, you can add a <strong><em>replaceString</em></strong> that replaces the banned patterns. This optional named parameter works differently when <strong><em>allow</em></strong> is true or false. To know more in detail, check <a href="https://api.flutter.dev/flutter/services/FilteringTextInputFormatter/replacementString.html"><strong><em>here</em></strong></a>.</p><h4><strong>2. FilteringTextInputFormatter.allow()</strong></h4><p>This is a named constructor that creates an input formatter to only allow the character that matches the given pattern. It has a positional parameter <strong><em>filterPattern</em></strong>. Here also, you can pass the <strong><em>replaceString</em></strong> optional named parameter.</p><h4><strong>3. FilteringTextInputFormatter.deny()</strong></h4><p>This is another named constructor that creates an input formatter to only block the character that matches the given pattern. It has also a positional parameter <strong><em>filterPattern</em></strong>. Here also, you can pass the <strong><em>replaceString</em></strong> optional named parameter.</p><h3>Example - Username Field</h3><p>Using the FilteringTextInputFormatter, we can format a text field where the user can type in a username and the rules for a valid username is</p><ul><li>Any alphabet and number are allowed.</li><li>A username can’t start with a number.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*IqjiEOUxXvQWMTW5iDJ_jA.png" /><figcaption>Check out the full code <a href="https://github.com/thecodexhub/flutter-textfield-input-formatter/blob/main/lib/view/username_view.dart">here</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*U4nRroUwETJEP5GQSCkp8A.gif" /></figure><p><strong><em>Note: </em></strong>Since only characters are removed from the text by this formatter, it attempts to keep the current <strong><em>[TextEditingValue.selection]</em></strong> at the values that it would have fallen at without the characters.</p><p>The <strong><em>selection</em></strong><em> </em>is a property in <strong><em>TextEditingValue</em></strong> that defines the range of text that is selected. In this instance, it typically constructs a collapsed selection at the specified offset.</p><p>A collapsed selection has zero characters as it begins and ends at the same offset and acts as an insertion point into the text. We will talk about this in the later part when we will create a custom <strong><em>TextInputFormatter</em></strong>.</p><h3><em>Static methods in FilteringTextInputFormatter</em></h3><p>There are two static properties in FilteringTextInputFormatter to make things a bit easier.</p><blockquote><strong>digitsOnly - </strong>A TextInputFormatter that takes only digits, i.e., 0 - 9.</blockquote><blockquote><strong>singleLineFormatter - </strong>This method demands a single line of input only.</blockquote><h3><em>About LengthLimitingTextInputFormatter</em></h3><p>The <strong><em>LengthLimitingTextInputFormatter</em></strong> is another built-in implementation of <strong><em>TextInputFormatter</em></strong> class. It stops users from entering more characters than are allowed.</p><p>The <strong><em>[TextEditingValue.selection]</em></strong> is preserved because this formatter mainly prevents new characters from being inserted into the text input field.</p><h3>Example - Phone Number Field</h3><p>Using the static methods of the <strong><em>FilteringTextInputFormatter </em></strong>and the <strong><em>LengthLimitingTextInputFormatter</em></strong>, we can format a text field where the user can type in a phone number and the rules for a valid phone number is</p><ul><li>Only digits are allowed.</li><li>Can not exceed 10 digits.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*rDzxK_5dGnhRJ4fOdrzhuA.png" /><figcaption>Check out the full code <a href="https://github.com/thecodexhub/flutter-textfield-input-formatter/blob/main/lib/view/phone_number_view.dart">here</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*VoO5aWMnQ7uA55jkpKcKug.gif" /></figure><h3><em>Custom TextInputFormatter</em></h3><p>To create our custom formatters we need to extend the <strong><em>TextInputFormatter</em></strong> class and implement the <strong><em>formatEditUpdate</em></strong> method. This method will be applied whenever any text is typed or cut/copy/pasted in the <em>TextField</em> or <em>TextFormField</em>.</p><p>The <strong><em>formatEditUpdate</em></strong> method is called with two parameters - <strong><em>oldValue</em></strong> and <strong><em>newValue</em></strong>. The <strong><em>oldValue</em></strong> represents an already existing value in the input field, and the <strong><em>newValue</em></strong> reflects the new value after any character(s) inserted in the text field. If the <strong><em>newValue</em></strong> qualifies our requirements, then we will return the <strong><em>newValue</em></strong>, otherwise, we will return the <strong><em>oldValue</em></strong>.</p><p>Whenever the user inserts or deletes any text in the <em>TextField</em> or <em>TextFormField</em>, the formatters will get executed in their provided order.</p><h3><em>Credit Card Number Formatter</em></h3><p>Let’s start by creating a custom input formatter that will format the credit card number entered by the user into the text field. Users can only enter digits in the TextField or TextFormField and the number will get formatted in the pattern <strong><em>XXXX XXXX XXXX XXXX</em></strong>.</p><p>So our goal for this formatter will be -</p><ul><li>Users can only enter digits.</li><li>A maximum of 16 digits can be entered.</li><li>After entering every 4 digits, when the user will insert another digit there will be a separator before the inserted digit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*-CsnlnaHMwDhsA7hq1GFtw.gif" /></figure><p>Create a class <strong><em>CardNumberFormatter</em></strong> that extends <strong><em>TextInputFormatter</em></strong>. Now we will implement the <strong><em>formatEditUpdate</em></strong> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*dXewuwsh5b6ISf8fHUYesw.png" /></figure><p>Let’s make it simple. Whenever the <strong><em>newValue</em></strong> length is greater than <strong><em>oldValue</em></strong>, i.e., a new digit has been entered, we will first check if the <strong><em>newValue</em></strong> length exceeds the <strong><em>sample</em></strong> length (16 digits + 3 separators → Length = 19 characters). If the <strong><em>newValue</em></strong> length exceeds then we should block that and return the <strong><em>oldValue</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*7VxWFFToZmDEnzeHXMa3NQ.png" /></figure><p>Now we should check if the user has inserted digits or not. Cause if the user enters any characters other than digits, then we need to restrict that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*26NNlFCYgMSHpXL4ZckczA.png" /></figure><p>Now, come to the final part. We will check if the last index of the <strong><em>newValue</em></strong> contains a separator in the <strong><em>pattern</em></strong>. If so, we will insert a separator and move the text selection offset to the next position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*_xxwYptFHai4Ny_gpSNvMA.png" /></figure><p>It’s done. Check out the full code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa44aa0531c00f2769ce3c3f9e22c9f1/href">https://medium.com/media/aa44aa0531c00f2769ce3c3f9e22c9f1/href</a></iframe><h3><em>Date of Birth Formatter</em></h3><p>Let’s create another custom input formatter and this time for asking the date of birth of the user. This time also, users are only allowed to insert digits. The pattern will be <strong><em>DD/MM/YYYY</em></strong> where the separators ‘/’ will be added by the formatters.</p><p>So our goal for this formatter will be -</p><ul><li>Users can only enter digits.</li><li>Users cannot enter a date greater than 31 and a month greater than 12. For example, if the user tries to enter 47 in the date portion, it will be edited to 04.</li><li>The sample date format is 15/06/2022 and the separator is ‘/’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*WL9JJiiEBZAQ9JbCseu_oQ.gif" /></figure><p>Create a class <strong><em>DOBFormatter</em></strong> that extends <strong><em>TextInputFormatter</em></strong>. Now we will implement the <strong><em>formatEditUpdate</em></strong> method.</p><p>Let’s start again from the same point. Whenever the <strong><em>newValue</em></strong> length is greater than <strong><em>oldValue</em></strong>, i.e., a new digit has been entered, we will first check if the <strong><em>newValue</em></strong> length exceeds the <strong><em>sample</em></strong> length (8 digits + 2 separators → Length = 10 characters). If the <strong><em>newValue</em></strong> length exceeds then we should block that and return the <strong><em>oldValue</em></strong>.</p><p>Then we should check if the user has inserted digits or not. Cause if the user enters any characters other than digits, then we need to restrict that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*hr8J_FEuVhiNY0_XaC2W2w.png" /></figure><p>Whenever there will be a requirement of adding a separator in the next index, that means either the user has entered the Date fully or the user has entered Date and Month completely. Accordingly, we will check for their validation. Let’s make this step simple. The date cannot exceed 31 and the month cannot be greater than 12. If the user tries to insert such a number it will be reduced to a single digit.</p><p>Go through the below code for a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEKYOjKQxr0kGYaMnVKjmw.png" /></figure><p>Finally, return the <strong><em>modifiedString </em></strong>if not null, otherwise, the user has inserted a valid date and month so we can go with the <strong><em>newValue</em></strong> itself.</p><p>Check out the full code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cec74db00e3dfc13870076982928a2e/href">https://medium.com/media/4cec74db00e3dfc13870076982928a2e/href</a></iframe><p>The full source for this tutorial can be found here👇</p><p><a href="https://github.com/thecodexhub/flutter-textfield-input-formatter">GitHub - thecodexhub/flutter-textfield-input-formatter: Learn how to format user input on-the-fly for a text field, minimize errors and improve user experience.</a></p><h3>Conclusion</h3><p>We now have a really good idea about how to format users’ input on-the-fly. In this tutorial, we walked through different examples of automatically formatting user input, giving our users a more seamless experience. This approach applies to any type of text input.</p><p>Let’s celebrate then! 🎉</p><p>If you have any queries or suggestions or questions, dive into the comments sections. Alternatively, you can reach out to me using <a href="https://www.instagram.com/thecodexhub/"><strong><em>Instagram</em></strong></a>, <a href="https://twitter.com/thecodexhub"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/in/sandip-pramanik-56a4a51b2/"><strong><em>LinkedIn</em></strong></a>, or <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>Email</em></strong></a>.</p><p>Please remember to applaud if this article was insightful and taught you something amazing. You know you can clap 50 times 🚀using that clap button. Give it a shot.😅</p><p>That’s it. Have a great day ahead!</p><p><a href="https://github.com/thecodexhub">thecodexhub - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71510af8a44c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/textinputformatter-in-flutter-format-users-input-on-the-fly-71510af8a44c">TextInputFormatter in Flutter - Format User’s Input on-the-fly</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Step Form with Flutter Bloc and Stepper Widget]]></title>
            <link>https://towardsdev.com/multi-step-form-with-flutter-bloc-and-stepper-widget-8d65b611cce1?source=rss-405bdb8169e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d65b611cce1</guid>
            <category><![CDATA[multi-step-form]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Sandip Pramanik]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 09:40:49 GMT</pubDate>
            <atom:updated>2022-06-17T06:59:36.800Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to build a multi-step form flow and how to use bloc to effectively isolate the presentation layer from the business logic layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aXGoEBqqp7Ri-rbQ" /><figcaption>Photo by <a href="https://unsplash.com/@tateisimikito?utm_source=medium&amp;utm_medium=referral">Jukan Tateisi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Through this article, we will discover how to facilitate users through a multi-step or multi-page form in your Flutter application using the Bloc library.</p><p>Before directly diving into building a multi-step form, let’s first elaborately discuss <em>what our aim is</em> and <em>what we are going to build</em>. This tutorial aims to provide you with sufficient knowledge about how to use the Bloc library to efficiently control the state of your app by following good practices. In this tutorial, we going to build a Checkout flow that consists of a few individual forms, where the form and each of the fields in it, will have their validation logic. And we will combine them later in this tutorial to get all the user details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xyz6JhvJUFO40j6Lu9LHHw.png" /><figcaption>Checkout Flow</figcaption></figure><p>The Checkout flow will have 3 forms that will be presented in 3 different steps or pages to collect different sets of information about the user.</p><ol><li>Personal Info Form → Name, Email, and Phone Number.</li><li>Billing Address Form → Street, Apartment, City, Country, and Postcode.</li><li>Payment Details → Card Name, Card Number, Expiry Date, and CVV.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*3fKtOqkYk5gFuhtAD850BQ.gif" /></figure><h3>Table of Contents</h3><ul><li><a href="#2fb3"><em>Create UserRepository package</em></a></li><li><a href="#4529"><em>Define User model</em></a></li><li><a href="#4048"><em>Repository class</em></a></li><li><a href="#f413"><em>Project Dependencies</em></a></li><li><a href="#ce1f"><em>Create RepositoryProvider for UserRepository</em></a></li><li><a href="#ae64"><em>Next Step - Create Forms</em></a></li><li><a href="#1c5d"><em>Create Models for the Forms</em></a></li><li><a href="#f2f0"><em>Create PersonalInfo Bloc</em></a></li><li><a href="#22d7"><em>View for PersonalInfo Form</em></a></li><li><a href="#23c8"><em>Take a break and Build other Forms</em></a></li><li><a href="#ecb1"><em>About Stepper Widget</em></a></li><li><a href="#5f28"><em>CheckoutState and CheckoutCubit</em></a></li><li><a href="#6752"><em>View for Checkout Stepper</em></a></li><li><a href="#f0ed"><em>Add Checkout Events to Form Submit and Cancel Buttons</em></a></li><li><a href="#81be"><em>Fetch the User Details in the ResultPage</em></a></li></ul><p>To keep track of the user and the user details, let’s start by creating a User model and a Repository that will take care of updating the User details and give us back the user details when required.</p><h3>Create UserRepository package</h3><p>We will construct internal packages to effectively structure our application design, maintain clear boundaries, and enhance both reusability and testability. The <strong><em>UserRepository</em></strong> will be in charge of abstracting the internal implementation details of updating and retrieving user information.</p><p>In this case, we will be using only the state variable for storing the user details, but we can change the internal implementation anytime later on (maybe storing on Firebase or using Local Storage) and our application will still be unaffected.</p><p>We can start by creating a new package <strong><em>packages/user_repository</em></strong> and to do so just run the following command inside the<strong><em>/packages</em></strong> directory.</p><pre><strong>$ flutter create --template=package user_repository</strong></pre><p>Now, we need to install only one dependency inside the newly created package’s <em>pubspec.yaml</em> file and that is <a href="https://pub.dev/packages/equatable"><strong><em>equatable</em></strong></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23f325e9e4a6664af191ec667e11ce11/href">https://medium.com/media/23f325e9e4a6664af191ec667e11ce11/href</a></iframe><p>Just like most of the packages, the <em>user_repository</em> will define its API surface via <strong><em>packages/user_repository/lib/user_repository.dart</em></strong> file. The package will be exposing an <strong><em>UserRepository</em></strong> as well as the <strong><em>User</em></strong> model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/723af4ff3776ec3d9bcebd8ed5a27db1/href">https://medium.com/media/723af4ff3776ec3d9bcebd8ed5a27db1/href</a></iframe><p>For this project purpose, we need to define a User model that consists of the above-mentioned properties - <em>Profile Information</em>, <em>Billing Address</em>, and <em>Payment Details</em>. Check out the below diagram to understand the model better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*P1BXA6xbQIsTR_vTSERguA.jpeg" /><figcaption>The User model consists of three models — PersonalInfo, BillingAddress, and Payment</figcaption></figure><h3>Define User model</h3><p>Let’s create the <strong>PersonalInfo</strong> model class, that extends <strong><em>Equatable</em></strong> to override equality comparisons and allow us to compare distinct instances of this class. Also, it is useful to define a factory <strong><em>empty</em></strong> the constructor of <strong>PersonalInfo</strong> so that we don’t have to deal with null objects and can always work with a concrete object.</p><p>Similarly, we need to create two more classes for <strong>BillingAddress</strong> and <strong>Payment</strong>. Then we can define our <strong>User</strong> model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d3bcd13e58ef9db7723592ca804aca9/href">https://medium.com/media/9d3bcd13e58ef9db7723592ca804aca9/href</a></iframe><h3>Repository class</h3><p>It’s time to finish the repository class. The actual mechanism of how a user is updated with different details, as well as how a user is fetched, is abstracted by the <strong>UserRepository</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d2163065dd15681b6a2f75942c77bca/href">https://medium.com/media/8d2163065dd15681b6a2f75942c77bca/href</a></iframe><p>The <strong>UserRepository</strong><em> </em>exposes three methods to update the personal information, address, and payment details individually. In addition, it exposes a method to get the current user details.</p><p>That’s it for the <strong>UserRepository</strong>. Next, let’s take a look at how to integrate it into the Flutter project.</p><h3>Project Dependencies</h3><p>We can now add our internal package via the path inside the <strong><em>pubspec.yaml</em></strong> at the root of the project. Besides, we need a few more packages that will serve different purposes.</p><ul><li><a href="https://pub.dev/packages/equatable"><strong><em>equatable</em></strong></a> → Overrides equality comparisons and allows to compare distinct instances of the class.</li><li><a href="https://pub.dev/packages/flutter_bloc"><strong><em>flutter_bloc</em></strong></a> → Provides flutter widgets to integrate blocs and cubits.</li><li><a href="https://pub.dev/packages/formz"><strong><em>formz</em></strong></a> → Simplifies form representation and validation.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cbb994747c783d88677f33e48a5008d/href">https://medium.com/media/9cbb994747c783d88677f33e48a5008d/href</a></iframe><h3>Create RepositoryProvider for UserRepository</h3><p>Before going into another discussion, let’s quickly complete our <strong><em>main.dart</em></strong> file. It will be responsible for providing a single instance of the <strong><em>UserRepository</em></strong><em> </em>to the application via <strong><em>RepositoryProvider</em></strong><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/062e0831a1f194863bfe3569087a3c17/href">https://medium.com/media/062e0831a1f194863bfe3569087a3c17/href</a></iframe><p>The <strong><em>RepositoryProvider </em></strong>provided by the flutter_bloc package is used as Dependency Injection (DI) that provides a single instance to multiple widgets within the subtree. Now we can access and call any methods exposed by our <strong><em>UserRepository</em></strong><em> </em>instance easily with <strong>context.read&lt;UserRepository&gt;()</strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*Yf4h3jpZ3yqRDNc-QR8YqA.jpeg" /><figcaption>Access UserRepository and its methods</figcaption></figure><h3>Next Step - Create Forms</h3><p>Now, we need to get input values from the user via <em>TextField</em>, validate them, and then call the needed method from <strong><em>UserRepository</em></strong> to update the details. Let’s talk in a brief about how we are going to do that. Remember, we have three sub-forms that need to be filled by the user before going to the final result page - <strong><em>PersonalInfo</em></strong>, <strong><em>BillingAddress</em></strong>, and <strong><em>Payment</em></strong>. They are three different forms that we will combine later in this tutorial using the <strong><em>Stepper</em></strong><em> </em>widget.</p><p>All of these three forms are very similar and if you understand one clearly, you can easily make the other two without getting stuck. Enough talking, let’s start by creating the first for - <strong><em>PersonalInfo</em></strong>. There will be three parts - <strong><em>models</em></strong>, <strong><em>bloc</em></strong>, and <strong><em>view</em></strong>. So it will be better to create a new folder named <strong><em>personal_info</em></strong>. Check out the folder structure in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*qOE2WnRJN3lo0I7JZumJBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*NQh67uM50emQBZ_4v5klMA.png" /><figcaption>Overall folder structure and personal_info folder structure</figcaption></figure><h3>Create Models for the Forms</h3><p>A <strong><em>Name</em></strong>,<em> </em><strong><em>Email</em></strong>, and <strong><em>PhoneNumber</em></strong><em> </em>input model are required for representing the form, encapsulating the validation logic, and updating the user’s personal information. All these input models will be made using the <a href="https://pub.dev/packages/formz"><strong><em>formz</em></strong></a> package so that we can work with a validated object rather than a primitive data type like <em>String</em>.</p><p>If you have never used the <a href="https://pub.dev/packages/formz"><strong><em>formz</em></strong></a><em> </em>package or heard about it, this is a very useful package and easy to understand, just go through the official documentation once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54041676e28725e6f0a089b855b77809/href">https://medium.com/media/54041676e28725e6f0a089b855b77809/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94cf0a794d6bd4b94dc4334057b3ed30/href">https://medium.com/media/94cf0a794d6bd4b94dc4334057b3ed30/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6774b5f6f18a6c487d84877a32782f7f/href">https://medium.com/media/6774b5f6f18a6c487d84877a32782f7f/href</a></iframe><p>Now you can easily create the input models for <strong><em>BillingAddress</em></strong><em> </em>and <strong><em>Payment</em></strong>. Remember to create different folders or directories for them and start writing their models.</p><p>The <strong><em>BillingAddress</em></strong><em> </em>consists of <em>Street, Apartment, City, Country, </em>and <em>Postcode, </em>whereas the <strong><em>Payment</em></strong><em> </em>consists of <em>CardName, CardNumber, ExpiryDate, </em>and <em>CvvNumber.</em></p><p>Don’t worry if you get stuck at any point while creating these models. You can always go to the repository and check out the full source code there. If you face any problem regarding <strong><em>BillingAddress</em></strong><em> </em>models, go to this <a href="https://github.com/thecodexhub/multi-page-form-with-bloc/tree/main/lib/billing_address/models"><strong><em>link</em></strong></a>. And if the problem is regarding <strong><em>Payment</em></strong><em> </em>models, check <a href="https://github.com/thecodexhub/multi-page-form-with-bloc/tree/main/lib/payment/models"><strong><em>here</em></strong></a>.</p><h3>Create PersonalInfo Bloc</h3><p>Time to start working on the <strong><em>PersonalInfoBloc</em></strong>.</p><p>Let’s declare the <strong><em>PersonalInfoEvent</em></strong> first. There will be 4 events in the personal info form, 3 of them notifies the bloc when the form fields will get changed, and the last one when the Submit button will be tapped.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb2bddd257da3606565203363e67f4fa/href">https://medium.com/media/bb2bddd257da3606565203363e67f4fa/href</a></iframe><p>The <strong><em>PersonalInfoState</em></strong><em> </em>consists of the <strong><em>Name</em></strong>, <strong><em>Email</em></strong><em>,</em> and <strong><em>PhoneNumber</em></strong> of the user, and the <strong><em>FormzStatus</em></strong>. The status will keep track of the overall validation status of the form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ece7fd4cc584341a70f754dfa3523c2/href">https://medium.com/media/2ece7fd4cc584341a70f754dfa3523c2/href</a></iframe><p>The <strong><em>PersonalInfoBloc</em></strong> bloc will be responsible for managing the <strong><em>PersonalInfoState</em></strong> of the form. It expresses APIs to <strong><em>FormSubmitted</em></strong> event, as well as gets notified when <em>name</em>/<em>email</em>/<em>phone number</em> are updated. It has a dependency on <strong><em>UserRepository</em></strong><em> </em>to update the personal information of the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f4b57ade5a5816b4d55ddb10da8e1a7/href">https://medium.com/media/8f4b57ade5a5816b4d55ddb10da8e1a7/href</a></iframe><h3>View for PersonalInfo Form</h3><p>The <strong><em>PersonalInfoPage</em></strong><em> </em>will create and provide the <strong><em>PersonalInfoBloc</em></strong><em> </em>to the <strong><em>PersonalInfoForm</em></strong>. It is a good practice to keep the production of blocs/cubits separate from where they are consumed. This way, you will be able to simply insert mock instances and test your view in isolation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/394884ecf76807ed7fb3a588052fa3cd/href">https://medium.com/media/394884ecf76807ed7fb3a588052fa3cd/href</a></iframe><p>The <strong><em>PersonalInfoForm</em></strong><em> </em>takes care of rendering the form based on the <strong><em>PersonalInfoState</em></strong> and invokes methods in response to user interactions that will eventually trigger all corresponding <strong><em>EventHandler</em></strong><em> </em>instances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/379fd1601218329787bbd2af7079de85/href">https://medium.com/media/379fd1601218329787bbd2af7079de85/href</a></iframe><p>Finally, we have now created a fully functional form. Great!</p><h3>Take a Break and Build other Forms</h3><p>Now you know how things are working inside the Form. The structure of the two other forms, <strong><em>BillingAddress</em></strong><em> </em>and <strong><em>Payment</em></strong><em> </em>will be the same and you can easily build them with the reference of the <strong><em>PersonalInfo</em></strong><em> </em>module.</p><p>Don’t get scared, every new thing looks and feels weird the first time. You have already gone through one module. And the other modules you can check out from <a href="https://github.com/thecodexhub/multi-page-form-with-bloc/tree/main/lib"><strong><em>here</em></strong></a>.</p><p>Still, if you got stuck, no need to worry. Let’s discuss them in the response or comments section and figure that out. Alternatively, you can contact me through some other platforms too. Check out at the end of the story for my social links.</p><p>We have now all the three fully-functional forms ready to get combined by the <strong><em>Stepper</em></strong><em> </em>widget. Before directly diving into the code, making some blocs and cubits again, let’s first check out what the <strong><em>Stepper</em></strong><em> </em>widget is, what its parameters are, and how that works.</p><h3>About Stepper Widget</h3><p>The <strong><em>Stepper</em></strong><em> </em>is a Material widget that is used to display a progress bar - a sequence of steps. Check out more about this <a href="https://api.flutter.dev/flutter/material/Stepper-class.html"><strong><em>widget</em></strong></a> in the Flutter docs once and you will have a clear what it is.</p><p>We are interested in three properties of the <em>Stepper </em>widget — <strong><em>currentStep</em></strong><em>, </em><strong><em>onStepTapped</em></strong><em>, </em>and<em> </em><strong><em>steps</em></strong><em>. </em>The <strong><em>steps</em></strong><em> </em>are the forms. The <strong><em>currentStep</em></strong><em> </em>is an index value that evaluates which step or form to be rendered. And the <strong><em>onStepTapped</em></strong><em> </em>is responsible to render a particular step if the tapped step is active or already submitted.</p><p>The default <strong><em>controlsBuilder</em></strong><em> </em>is responsible for automatically creating one submit button and one back button to go back to the previous step. But we are going to control the navigation of the forms, move forward, and backward inside the Stepper from the Form Submit and Cancel buttons.</p><p>That means we need a state variable let’s say <strong><em>activeStepperIndex</em></strong><em> </em>that will indicate the currently active step in the Form. And <strong><em>onStepTapped</em></strong>, the index of the tapped step will be assigned to the <strong><em>activeStepperIndex</em></strong><em> </em>variable. Similarly, we need two more functionality <strong><em>stepContinued</em></strong><em> </em>and <strong><em>stepCancelled</em></strong>, that will notify the widget when the Submit button and the Cancel button will be tapped.</p><h3>CheckoutState and CheckoutCubit</h3><p>Let’s create a Cubit that will serve the above-said purpose.</p><p>The <strong><em>CheckoutState </em></strong>consists of only one variable to keep track of the currently active state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dfdca487cb4d018ba2cbb171787a935/href">https://medium.com/media/0dfdca487cb4d018ba2cbb171787a935/href</a></iframe><p>The <strong><em>CheckoutCubit</em></strong><em> </em>is responsible for managing the <strong><em>activeStepperIndex</em></strong><em> </em>inside the <strong><em>CheckoutState</em></strong>. It exposes APIs to <strong><em>stepTapped</em></strong><em>, </em><strong><em>stepContinued</em></strong><em>, </em>and <strong><em>stepCancelled</em></strong><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ce3cb0644c976edabe66267434ba0d/href">https://medium.com/media/66ce3cb0644c976edabe66267434ba0d/href</a></iframe><blockquote>Note: Because the <strong>CheckoutState</strong> is simple and localized, we used a Cubit instead of a Bloc here. Even without events, we can get a good idea of what happened by seeing the transitions from one state to the next, and our code is much simpler and more concise.</blockquote><h3>View for Checkout Stepper</h3><p>The <strong><em>CheckoutPage</em></strong><em> </em>will create and provide <strong><em>CheckoutCubit</em></strong><em> </em>to the <strong><em>CheckoutStepper</em></strong><em> </em>widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4dcb9c4dcf626b7ff78f85d9cf5583/href">https://medium.com/media/dd4dcb9c4dcf626b7ff78f85d9cf5583/href</a></iframe><p>The <strong><em>CheckoutStepper</em></strong><em> </em>will take care of rendering the step or the form depending upon the currently active step’s index and invokes methods in response to the user interaction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73773c76c1a0cffccfdcbdd332285a65/href">https://medium.com/media/73773c76c1a0cffccfdcbdd332285a65/href</a></iframe><h3>Add Checkout Events to Form Submit and Cancel Buttons</h3><p>Let’s also finish the stepper by adding the event calls from the Submit and the Cancel buttons from each form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941d532d385d21ab189e3eb11edbd050/href">https://medium.com/media/941d532d385d21ab189e3eb11edbd050/href</a></iframe><p>Also, on the last step of the Stepper, i.e., on the <strong><em>PaymentForm</em></strong> page’s <strong><em>Submit </em></strong>button, we will navigate to a new page, <strong><em>ResultPage </em></strong>that will show all the user details that we have been tired of collecting for so long 😅.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7287f6e439c70ac23efff5ae2df9ca5/href">https://medium.com/media/d7287f6e439c70ac23efff5ae2df9ca5/href</a></iframe><h3>Fetch the User Details in the ResultPage</h3><p>Great! We are on the last step now. And the job is to read the user details from the <strong><em>UserRepository</em></strong><em> </em>and show them in the <strong><em>ResultPage</em></strong><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70d54a25bd8901cd85b7cb3c996f1f05/href">https://medium.com/media/70d54a25bd8901cd85b7cb3c996f1f05/href</a></iframe><p>The full source for this tutorial can be found here👇</p><p><a href="https://github.com/thecodexhub/multi-page-form-with-bloc">GitHub - thecodexhub/multi-page-form-with-bloc: Learn how to build a multi-step form flow and how to use bloc to effectively isolate the presentation layer from the business logic layer.</a></p><h3>Conclusion</h3><p>We now have a really good Multi-step Form implementation, and we’ve used the Bloc Library to effectively isolate our presentation layer from the business logic layer.</p><p>Let’s celebrate then! 🎉</p><p>If you have any queries or suggestions or questions, dive into the comments sections. Alternatively, you can reach out to me using <a href="https://www.instagram.com/thecodexhub/"><strong><em>Instagram</em></strong></a>, <a href="https://twitter.com/thecodexhub"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/in/sandip-pramanik-56a4a51b2/"><strong><em>LinkedIn</em></strong></a>, or <a href="/service/mailto:thecodexhubofficial@gmail.com"><strong><em>Email</em></strong></a>.</p><p>Please remember to applaud if this article was insightful and taught you something amazing. Actually, you know you can clap 50 times 🚀using that clap button. Give it a shot.😅</p><p>That’s it. Have a great day ahead!</p><p><a href="https://github.com/thecodexhub">thecodexhub - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d65b611cce1" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/multi-step-form-with-flutter-bloc-and-stepper-widget-8d65b611cce1">Multi-Step Form with Flutter Bloc and Stepper Widget</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>