<?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 Kiran Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Kiran Kulkarni on Medium]]></description>
        <link>https://medium.com/@kiran.kulkarni_3903?source=rss-44bbbaee7cdd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qjKisMstx8-zgnfCK8PTaA.jpeg</url>
            <title>Stories by Kiran Kulkarni on Medium</title>
            <link>https://medium.com/@kiran.kulkarni_3903?source=rss-44bbbaee7cdd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kiran.kulkarni_3903/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter BlocProvider vs BlocProvider.value — A Practical Guide]]></title>
            <link>https://blog.nonstopio.com/flutter-blocprovider-vs-blocprovider-value-a-practical-guide-8661cce2c0a5?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8661cce2c0a5</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[flutter-bloc-pattern]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 10:54:37 GMT</pubDate>
            <atom:updated>2025-09-24T10:54:37.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter BlocProvider vs BlocProvider.value — A Practical Guide</h3><p>When working with <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a>, one of the common questions is:</p><p>👉 <strong>When should I use </strong><strong>BlocProvider vs </strong><strong>BlocProvider.value?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S20h5xBQgwo8QinBIZCaTQ@2x.png" /></figure><p>This blog explains the difference with a real-world AuthBloc example, shows how to pass blocs across pages, and demonstrates how to manage bloc disposal properly.</p><h3>BlocProvider vs BlocProvider.value</h3><h3>BlocProvider</h3><ul><li>Creates a new bloc instance using the create function.</li><li>Automatically closes the bloc when the widget is disposed.</li><li>Best when you want the bloc’s lifecycle tied to a specific widget.</li></ul><pre>BlocProvider(<br>  create: (context) =&gt; AuthBloc(),<br>  child: LoginPage(),<br>);</pre><p>Here, when LoginPage is removed, the AuthBloc is automatically closed. ✅</p><h3>BlocProvider.value</h3><ul><li>Provides an <strong>existing bloc instance</strong> to the widget tree.</li><li>Does <strong>not</strong> automatically manage disposal.</li><li>Best when passing an already created bloc into a new widget or route.</li></ul><pre>BlocProvider.value(<br>  value: context.read&lt;AuthBloc&gt;(),<br>  child: ProfilePage(),<br>);</pre><p>Here, you are responsible for deciding <strong>when</strong> to close the bloc.</p><h3>Why Context Matters</h3><p>One of the most common mistakes with bloc is assuming that a bloc provided in <strong>Page 1</strong> is automatically available in <strong>Page 2</strong>.</p><p>Here’s what actually happens:</p><pre>📱 Page 1 (Route: &#39;/&#39;)<br>├── BlocProvider (creates BlocA instance)<br>    └── Widget Tree<br>        ├── Widget 1 ✅ (can access BlocA)<br>        ├── Widget 2 ✅ (can access BlocA)<br>        └── Widget 3 ✅ (can access BlocA)📱 Page 2 (Route: &#39;/second&#39;)<br>└── Widget Tree<br>    ├── Widget A ❌ (cannot access BlocA - different context!)<br>    ├── Widget B ❌ (cannot access BlocA - different context!)<br>    └── Widget C ❌ (cannot access BlocA - different context!)</pre><p>👉 Each route in Flutter has its <strong>own widget tree and context</strong>.<br> So, if you want to <strong>reuse the same bloc</strong> across pages, you must pass it explicitly using BlocProvider.value.</p><h3>Real-World Example: Auth Flow</h3><p>Let’s build a simple authentication flow:</p><ol><li>AuthBloc manages login/logout.</li><li>LoginPage lets the user log in.</li><li>ProfilePage displays the user’s name and allows logout.</li></ol><h3>AuthBloc</h3><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>abstract class AuthEvent {}<br>class LoginRequested extends AuthEvent {<br>  final String username;<br>  LoginRequested(this.username);<br>}<br>class LogoutRequested extends AuthEvent {}<br><br><br>abstract class AuthState {}<br>class Unauthenticated extends AuthState {}<br>class Authenticated extends AuthState {<br>  final String username;<br>  Authenticated(this.username);<br>}<br>class AuthBloc extends Bloc&lt;AuthEvent, AuthState&gt; {<br>  AuthBloc() : super(Unauthenticated()) {<br>    on&lt;LoginRequested&gt;((event, emit) {<br>      emit(Authenticated(event.username));<br>    });<br>    on&lt;LogoutRequested&gt;((event, emit) {<br>      emit(Unauthenticated());<br>      // 🔐 Close the bloc when logout is requested<br>      close();<br>    });<br>  }<br>}</pre><h3>LoginPage</h3><pre>class LoginPage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Login&quot;)),<br>      body: Center(<br>        child: ElevatedButton(<br>          onPressed: () {<br>            context.read&lt;AuthBloc&gt;().add(LoginRequested(&quot;Tara&quot;));<br>Navigator.push(<br>              context,<br>              MaterialPageRoute(<br>                builder: (_) =&gt; BlocProvider.value(<br>                  value: context.read&lt;AuthBloc&gt;(),<br>                  child: ProfilePage(),<br>                ),<br>              ),<br>            );<br>          },<br>          child: Text(&quot;Login as Tara&quot;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>ProfilePage</h3><pre>class ProfilePage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Profile Page&quot;)),<br>      body: Center(<br>        child: BlocBuilder&lt;AuthBloc, AuthState&gt;(<br>          builder: (context, state) {<br>            if (state is Authenticated) {<br>              return Column(<br>                mainAxisAlignment: MainAxisAlignment.center,<br>                children: [<br>                  Text(&quot;Hello, ${state.username}!&quot;),<br>                  ElevatedButton(<br>                    onPressed: () {<br>                      context.read&lt;AuthBloc&gt;().add(LogoutRequested());<br>                      Navigator.pop(context); // back to login<br>                    },<br>                    child: Text(&quot;Logout&quot;),<br>                  ),<br>                ],<br>              );<br>            }<br>            return Text(&quot;Not logged in&quot;);<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Lifecycle Summary</h3><ul><li><strong>BlocProvider</strong> → bloc is auto-closed with the widget.</li><li><strong>BlocProvider.value</strong> → you provide an existing bloc, and you <strong>own its lifecycle</strong>.</li><li>By calling close() in the LogoutRequested handler, you ensure that once the user logs out, the bloc is disposed immediately.</li></ul><p>⚠️ <strong>Important Note</strong>:<br> If you close the bloc in LogoutRequested, you can’t reuse the same bloc for another login. You’ll need to create a <strong>new </strong><strong>AuthBloc</strong> when navigating back to LoginPage.</p><p>✅ With this pattern, your bloc lifecycle is <strong>clean and predictable</strong>, and your UI stays free from manual close() calls.</p><p>Here to make the community stronger by sharing our knowledge. <a href="https://medium.com/@kiran.kulkarni_3903">Follow me</a> and <a href="https://medium.com/nonstopio">my team</a> to stay updated on the latest and greatest in the web &amp; mobile tech world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8661cce2c0a5" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/flutter-blocprovider-vs-blocprovider-value-a-practical-guide-8661cce2c0a5">Flutter BlocProvider vs BlocProvider.value — A Practical Guide</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Event Handling with bloc_concurrency in Flutter]]></title>
            <link>https://blog.nonstopio.com/mastering-event-handling-with-bloc-concurrency-in-flutter-56765864fcea?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/56765864fcea</guid>
            <category><![CDATA[bloc-concurrency]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[flutter-web]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 09:46:25 GMT</pubDate>
            <atom:updated>2025-08-05T09:46:25.077Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with BLoC in Flutter, handling <strong>rapid or repeated events</strong> gracefully is crucial. Users may tap buttons rapidly, type quickly into search fields, or trigger animations repeatedly. Without control, this can lead to race conditions, dropped frames, or duplicated API calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aysh58dRYbn6PUUI8D-zDQ@2x.png" /></figure><p>To solve this, the <a href="https://pub.dev/packages/bloc_concurrency">bloc_concurrency</a> This package gives you <strong>powerful transformers</strong> to control how your app processes events.</p><p>This blog walks through:</p><ul><li>What each transformer does</li><li>When to use it</li><li>A fun visual <strong>ball-and-bridge</strong> Flutter demo to see the effects in action</li></ul><h3>🎯 Why bloc_concurrency?</h3><p>By default, BLoC uses the sequential() strategy — events are processed one-by-one, in the order received.</p><p>But sometimes, we need smarter behaviors:</p><ul><li>Ignore new events while one is in progress</li><li>Cancel old ones and only process the latest</li><li>Handle multiple events simultaneously</li><li>Rate-limit or debounce high-frequency events</li></ul><h3>🛠️ Event Processing Transformers</h3><p>These controls determine <strong>how events are processed</strong>, especially when multiple events are triggered simultaneously.</p><h3>✅ sequential()</h3><ul><li><strong>Behavior:</strong> Waits for the current event to finish before starting the next.</li><li><strong>Default BLoC strategy</strong></li><li><strong>Use Case:</strong> Ordered tasks — multi-step forms or animations.</li></ul><h3>✅ concurrent()</h3><ul><li><strong>Behavior:</strong> Processes all incoming events in parallel.</li><li><strong>Use Case:</strong> Independent jobs like logging, syncing multiple items, etc.</li></ul><h3>✅ droppable()</h3><ul><li><strong>Behavior:</strong> Drops any new event while the current one is still processing.</li><li><strong>Use Case:</strong> Prevents multiple clicks, duplicate API calls.</li></ul><blockquote><em>Example: If an API call takes 2 seconds, all incoming events during that time are ignored.</em></blockquote><h3>✅ restartable()</h3><ul><li><strong>Behavior:</strong> Cancels the current event when a new one comes in; only the latest gets processed.</li><li><strong>Use Case:</strong> Real-time search or filtering where only the <strong>latest input</strong> matters.</li></ul><h3>⏱️ Event Timing Transformers (rxdart required)</h3><p>These control <strong>when</strong> an event is even allowed to reach the BLoC:</p><h3>✅ debounceTime(Duration)</h3><ul><li><strong>Behavior:</strong> Waits for a “quiet period” (e.g., 600ms) before sending the latest event.</li><li><strong>Use Case:</strong> Search fields — fire only after user <strong>stops typing</strong>.</li></ul><h3>✅ throttleTime(Duration)</h3><ul><li><strong>Behavior:</strong> Accepts one event per time window (e.g., 1s); ignores the rest.</li><li><strong>Use Case:</strong> Prevents spammy buttons or scroll gestures.</li></ul><h3>🧪 The Bridge &amp; Ball Demo App 🏗️</h3><p>To make these behaviors easier to visualize, we built a <strong>fun demo app</strong> in Flutter.</p><ul><li>Each <strong>ball</strong> = one event (SendBallEvent)</li><li>The <strong>bridge</strong> = processing stage</li><li>The <strong>transformer</strong> decides how the bridge lets balls pass</li></ul><p>Send multiple balls and <strong>see how each transformer behaves</strong> in real-time!</p><h3>📲 Demo Tabs Include</h3><p>Each tab uses a different transformer strategy:</p><h3>🔵 Sequential Bridge</h3><ul><li><strong>Transformer:</strong> sequential()</li><li><strong>Behavior:</strong> Each ball waits for the previous to finish.</li><li><strong>Use Case:</strong> Ordered execution like animations or queues.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*p16Fi764qweiYza1U1UK2A.gif" /><figcaption>sequential.gif</figcaption></figure><h3>🟢 Concurrent Bridge</h3><ul><li><strong>Transformer:</strong> concurrent()</li><li><strong>Behavior:</strong> All balls cross the bridge simultaneously.</li><li><strong>Use Case:</strong> Parallel tasks that don’t depend on one another.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ym5z5isqgD16tqIlzwSRSQ.gif" /><figcaption>concurrent.gif</figcaption></figure><h3>🟠 Droppable Bridge</h3><ul><li><strong>Transformer:</strong> droppable()</li><li><strong>Behavior:</strong> If a ball is crossing, any new ball is dropped.</li><li><strong>Use Case:</strong> Prevents double taps or fast repeat actions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wfFtPQoEIzuzfOR1mQNS6g.gif" /><figcaption>droppable.gif</figcaption></figure><h3>🟣 Restartable Bridge</h3><ul><li><strong>Transformer:</strong> restartable()</li><li><strong>Behavior:</strong> Cancels the current ball and only allows the latest to cross.</li><li><strong>Use Case:</strong> Search/filter fields where only the <strong>latest input</strong> matters.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BqzWY5sSFROc_YpYbLRJZQ.gif" /><figcaption>restartable.gif</figcaption></figure><h3>🟧 Debounce Bridge</h3><ul><li><strong>Transformer:</strong> debounceTime(Duration)</li><li><strong>Behavior:</strong> Waits for the user to <strong>stop typing (600ms)</strong> before sending the ball.</li><li><strong>Use Case:</strong> Search bars, form validation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fPeeULTRRVgJrs5yKfV4sQ.gif" /><figcaption>debounce.gif</figcaption></figure><h3>🔵 Throttle Bridge</h3><ul><li><strong>Transformer:</strong> throttleTime(Duration)</li><li><strong>Behavior:</strong> Allows only <strong>one ball per second</strong>, drops the rest.</li><li><strong>Use Case:</strong> Rate-limiting taps, sliders, or network pings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_yvN0-HyXeh5_liU03J2dQ.gif" /><figcaption>throttle.gif</figcaption></figure><h3>⚙️ Setup the Demo Locally</h3><pre># pubspec.yaml<br>dependencies:<br>  flutter_bloc: ^8.1.3<br>  bloc_concurrency: ^0.2.2<br>  equatable: ^2.0.5<br>  rxdart: ^0.27.0</pre><p>Use BLoC like this:</p><pre>on&lt;Event&gt;(<br>  handler,<br>  transformer: droppable(), // or restartable(), debounceTransformer(), etc.<br>);</pre><p>For debounceTime and throttleTime, use custom Rx transformers with rxdart:</p><pre>EventTransformer&lt;E&gt; debounceTransformer&lt;E&gt;(Duration duration) {<br>  return (events, mapper) =&gt; events.debounceTime(duration).flatMap(mapper);<br>}</pre><h3>✅ Final Thoughts</h3><p>Using bloc_concurrency gives you fine-grained control over how your BLoCs respond under load — improving performance, reliability, and user experience.</p><p>Combine it with rxdart for even more flexibility using debounceTime() and throttleTime().</p><p>You can check this <a href="https://flutter-bloc-concurrency-demo.web.app/"><strong>Demo</strong></a> <strong>and this </strong><a href="https://github.com/kirannonstop/flutter_bloc_concurrency_demo"><strong>GitHub</strong></a></p><p>Here to make the community stronger by sharing our knowledge. <a href="https://medium.com/@kiran.kulkarni_3903">Follow me</a> and <a href="https://medium.com/nonstopio">my team</a> to stay updated on the latest and greatest in the web &amp; mobile tech world.</p><h3>📎 Resources</h3><ul><li><a href="https://pub.dev/packages/bloc_concurrency">bloc_concurrency on pub.dev</a></li><li><a href="https://pub.dev/packages/rxdart">rxdart on pub.dev</a></li><li>Flutter BLoC Package</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56765864fcea" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/mastering-event-handling-with-bloc-concurrency-in-flutter-56765864fcea">🔄 Mastering Event Handling with bloc_concurrency in Flutter</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Supercharge Your Flutter Workflow with Mason: Build and Reuse App Templates Easily]]></title>
            <link>https://blog.nonstopio.com/supercharge-your-flutter-workflow-with-mason-build-and-reuse-app-templates-easily-821dde400106?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/821dde400106</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[brick]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[masons]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 07:39:56 GMT</pubDate>
            <atom:updated>2025-07-02T04:42:43.570Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A step-by-step guide to creating and using Flutter app bricks with web &amp; test support.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mA5yyQTikX77jhNnTrZZDg@2x.png" /></figure><h3>📌 Introduction</h3><p>I create these blogs primarily for my reference, but you’re welcome to refer to them as well :)</p><p>If you’re working on multiple Flutter apps or feature modules, you’ve probably duplicated the same boilerplate over and over.</p><p>Say goodbye to copy-paste fatigue — <strong>Mason</strong> makes it easy to <strong>scaffold reusable Flutter app templates</strong> (called <em>bricks</em>) with one command.</p><p>In this guide, you’ll learn how to:</p><p>✅ Install &amp; set up Mason<br> ✅ Create your own flutter_example_app brick (with main.dart, pubspec.yaml, test/, web/)<br> ✅ Use it to generate new projects instantly<br> ✅ Add it to your team&#39;s long-term development toolkit</p><h3>🧱 What Is Mason?</h3><p>Mason is like Yeoman or Cookiecutter for Dart/Flutter. You define reusable templates (called <em>bricks</em>) and generate them on demand.</p><h3>🚀 Step-by-Step Setup</h3><h3>✅ Step 1: Install Mason</h3><pre>dart pub global activate mason_cli</pre><p>Make sure Mason is available:</p><pre>mason --version</pre><blockquote><em>🔄 Restart your terminal if </em><em>mason is not recognized.</em></blockquote><h3>✅ Step 2: Set Up Your Project</h3><p>Make sure your repo has this layout:</p><pre>my_flutter_repo/<br>├── bricks/                ← Place for all your custom bricks<br>├── examples/              ← Generated apps/features go here<br>├── mason.yaml             ← Root mason config</pre><p>Create the bricks folder if it doesn&#39;t exist:</p><pre>mkdir bricks</pre><h3>✅ Step 3: Create a Full Flutter App Brick</h3><p>Inside bricks/, run:</p><pre>mason new flutter_example_app</pre><p>This will generate:</p><pre>bricks/flutter_example_app/<br>├── __brick__/<br>├── brick.yaml</pre><p>Replace the contents as follows:</p><h3>📄 brick.yaml</h3><pre>name: flutter_example_app<br>description: A full Flutter app with web and test support.<br>vars:<br>  name:<br>    type: string<br>    description: What is your app called?<br>    default: example_app</pre><h3>📂 Inside __brick__/, create:</h3><pre>__brick__/<br>├── lib/<br>│   └── main.dart<br>├── web/<br>│   └── index.html<br>├── test/<br>│   └── smoke_test.dart<br>├── pubspec.yaml</pre><h4>✅ lib/main.dart</h4><pre>import &#39;package:flutter/material.dart&#39;;<br>void main() {<br>  runApp(const MyApp());<br>}<br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;{{name}}&#39;,<br>      theme: ThemeData(primarySwatch: Colors.blue),<br>      home: const HomePage(),<br>    );<br>  }<br>}<br>class HomePage extends StatelessWidget {<br>  const HomePage({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;{{name.pascalCase()}}&#39;)),<br>      body: const Center(child: Text(&#39;Welcome to {{name}}!&#39;)),<br>    );<br>  }<br>}</pre><h4>✅ test/smoke_test.dart</h4><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br><br>void main() {<br>  test(&#39;smoke test&#39;, () {<br>    expect(1 + 1, equals(2));<br>  });<br>}</pre><h4>✅ web/index.html</h4><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;{{name}}&lt;/title&gt;<br>    &lt;link rel=&quot;manifest&quot; href=&quot;manifest.json&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script src=&quot;main.dart.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h4>✅ pubspec.yaml</h4><pre>name: {{name.snakeCase()}}<br>description: A new Flutter project called {{name}}.<br><br>environment:<br>  sdk: &quot;&gt;=3.8.0 &lt;4.0.0&quot;<br>dependencies:<br>  flutter:<br>    sdk: flutter<br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  flutter_lints: ^3.0.0<br>flutter:<br>  uses-material-design: true</pre><h3>✅ Step 4: Add Brick to Root mason.yaml</h3><p>Create mason.yaml In the project root if missing:</p><pre>bricks:<br>  flutter_example_app:<br>    path: bricks/flutter_example_app</pre><p>Then run:</p><pre>mason get</pre><h3>✅ Step 5: Generate a Flutter App</h3><p>To create a new app:</p><pre>mason make flutter_example_app --output-dir examples/hello_app</pre><p>Follow the prompt:</p><pre>What is your app called? hello_app</pre><p>You’ll get:</p><pre>examples/hello_app/<br>├── lib/<br>├── test/<br>├── web/<br>└── pubspec.yaml</pre><h3>✅ Step 6: Run the App</h3><pre>cd examples/hello_app<br>fvm flutter pub get<br>fvm flutter test<br>fvm flutter run -d chrome</pre><h3>✅ Bonus: Pin Flutter for Specific Version with FVM</h3><pre>fvm use 3.32.5</pre><p>To auto-use this version in the future:</p><pre>// .fvm/fvm_config.json<br>{<br>  &quot;flutterSdkVersion&quot;: &quot;3.32.5&quot;<br>}</pre><h3>✅ Bonus Tips</h3><ul><li>Run mason list to see available bricks</li><li>Use -c config.json to skip prompts</li><li>Add reusable feature Bricks to scaffold BLoC, Cubit, etc.</li></ul><h3>🎉 Conclusion</h3><p>Mason saves hours of boilerplate and setup time. Whether you’re generating apps, widgets, or feature modules, you can use bricks to <strong>standardize and scale</strong> your development workflow.</p><blockquote><em>🧠 You can even create bricks for:</em></blockquote><ul><li>REST client scaffolds</li><li>Firebase auth modules</li><li>Admin dashboards</li><li>GoRouter layouts</li></ul><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@kiran.kulkarni_3903"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><p><strong>References</strong></p><p><a href="https://github.com/ProjectAJ14/ns_mason_bricks">https://github.com/ProjectAJ14/ns_mason_bricks</a><br><a href="https://github.com/ProjectAJ14/flutter_ns_template">https://github.com/ProjectAJ14/flutter_ns_template</a><br><a href="https://github.com/ProjectAJ14/flutter_getx_mason">https://github.com/ProjectAJ14/flutter_getx_mason</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821dde400106" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/supercharge-your-flutter-workflow-with-mason-build-and-reuse-app-templates-easily-821dde400106">🔨 Supercharge Your Flutter Workflow with Mason: Build and Reuse App Templates Easily</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Keyboard-Accessible Custom Checkbox Widget in Flutter]]></title>
            <link>https://blog.nonstopio.com/building-a-keyboard-accessible-custom-checkbox-widget-in-flutter-fce891d3e140?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce891d3e140</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[focus]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[checkbox]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Tue, 27 May 2025 07:03:24 GMT</pubDate>
            <atom:updated>2025-05-27T07:03:24.767Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern app development, accessibility isn’t just a nice-to-have feature — it’s essential. Today, we’ll explore how to create a custom checkbox widget in Flutter that provides excellent keyboard accessibility while maintaining clean, maintainable code. This widget will allow users to interact with checkboxes using keyboard navigation, making your app more inclusive for users who rely on keyboard input or assistive technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZZPFv7gQiWoX2o5.png" /></figure><h3>The Problem</h3><p>Flutter’s built-in Checkbox widget handles mouse/touch interactions well, but sometimes we need more control over keyboard interactions, focus management, and custom behaviors. Our FocusedCheckBox widget solves these challenges by:</p><ul><li>Providing consistent keyboard navigation (Enter and Space key support)</li><li>Managing focus states properly</li><li>Allowing flexible focus node management</li><li>Maintaining clean separation of concerns</li></ul><h3>The Complete Solution</h3><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br><br>class FocusedCheckBox extends StatefulWidget {<br>  final bool isChecked;<br>  final Function(bool) onChanged;<br>  final FocusNode? focusNode;<br>  <br>  const FocusedCheckBox({<br>    super.key,<br>    required this.isChecked,<br>    required this.onChanged,<br>    this.focusNode,<br>  });<br>  @override<br>  State&lt;FocusedCheckBox&gt; createState() =&gt; _FocusedCheckBoxState();<br>}<br>class _FocusedCheckBoxState extends State&lt;FocusedCheckBox&gt; {<br>  late FocusNode _focusNode;<br>  bool _isInternalFocusNode = false;<br>  @override<br>  void initState() {<br>    super.initState();<br>    _initializeFocusNode();<br>  }<br>  @override<br>  void didUpdateWidget(FocusedCheckBox oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br>    <br>    if (widget.focusNode != oldWidget.focusNode) {<br>      _disposeFocusNode();<br>      _initializeFocusNode();<br>    }<br>  }<br>  void _initializeFocusNode() {<br>    if (widget.focusNode != null) {<br>      _focusNode = widget.focusNode!;<br>      _isInternalFocusNode = false;<br>    } else {<br>      _focusNode = FocusNode();<br>      _isInternalFocusNode = true;<br>    }<br>    <br>    _focusNode.onKeyEvent = _handleKeyEvent;<br>  }<br>  void _disposeFocusNode() {<br>    _focusNode.onKeyEvent = null;<br>    if (_isInternalFocusNode) {<br>      _focusNode.dispose();<br>    }<br>  }<br>  KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {<br>    if (event is KeyDownEvent) {<br>      if (event.logicalKey == LogicalKeyboardKey.enter ||<br>          event.logicalKey == LogicalKeyboardKey.space) {<br>        widget.onChanged(!widget.isChecked);<br>        return KeyEventResult.handled;<br>      }<br>    }<br>    return KeyEventResult.ignored;<br>  }<br>  @override<br>  void dispose() {<br>    _disposeFocusNode();<br>    super.dispose();<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return Checkbox(<br>      focusNode: _focusNode,<br>      value: widget.isChecked,<br>      onChanged: (isChecked) {<br>        widget.onChanged(isChecked ?? false);<br>      },<br>    );<br>  }<br>}</pre><h3>Breaking Down the Implementation</h3><h3>1. Widget Declaration and Properties</h3><pre>class FocusedCheckBox extends StatefulWidget {<br>  final bool isChecked;<br>  final Function(bool) onChanged;<br>  final FocusNode? focusNode;</pre><p>Our widget accepts three parameters:</p><ul><li>isChecked: The current state of the checkbox (controlled by parent)</li><li>onChanged: Callback function when the checkbox state changes</li><li>focusNode: Optional external focus node for advanced focus management</li></ul><p>This design follows Flutter’s convention of separating state management between parent and child widgets, making it reusable and predictable.</p><h3>2. State Variables</h3><pre>late FocusNode _focusNode;<br>bool _isInternalFocusNode = false;</pre><p>We maintain two crucial state variables:</p><ul><li>_focusNode: The actual focus node used by the checkbox</li><li>_isInternalFocusNode: A flag tracking whether we created the focus node internally</li></ul><p>This tracking is essential for proper memory management — we only dispose of focus nodes we created ourselves.</p><h3>3. Initialization Logic</h3><pre>@override<br>void initState() {<br>  super.initState();<br>  _initializeFocusNode();<br>}</pre><p>The initState() method runs once when the widget is first created. We immediately set up our focus node to ensure the widget is ready for interaction from the start.</p><h3>4. Handling Widget Updates</h3><pre>@override<br>void didUpdateWidget(FocusedCheckBox oldWidget) {<br>  super.didUpdateWidget(oldWidget);<br>  <br>  if (widget.focusNode != oldWidget.focusNode) {<br>    _disposeFocusNode();<br>    _initializeFocusNode();<br>  }<br>}</pre><p>The didUpdateWidget() method is called whenever the parent widget rebuilds with new properties. We check if the focus node has changed and reinitialize it if necessary. This ensures our widget correctly adapts to dynamic focus node changes.</p><h3>5. Focus Node Initialization</h3><pre>void _initializeFocusNode() {<br>  if (widget.focusNode != null) {<br>    _focusNode = widget.focusNode!;<br>    _isInternalFocusNode = false;<br>  } else {<br>    _focusNode = FocusNode();<br>    _isInternalFocusNode = true;<br>  }<br>  <br>  _focusNode.onKeyEvent = _handleKeyEvent;<br>}</pre><p>This method handles the dual nature of focus node management:</p><ul><li>If an external focus node is provided, we use it (useful for complex focus management scenarios)</li><li>If no focus node is provided, we create our own</li><li>We always attach our key event handler regardless of the focus node source</li></ul><h3>6. Keyboard Event Handling</h3><pre>KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {<br>  if (event is KeyDownEvent) {<br>    if (event.logicalKey == LogicalKeyboardKey.enter ||<br>        event.logicalKey == LogicalKeyboardKey.space) {<br>      widget.onChanged(!widget.isChecked);<br>      return KeyEventResult.handled;<br>    }<br>  }<br>  return KeyEventResult.ignored;<br>}</pre><p>This is where the magic happens for keyboard accessibility:</p><ul><li>We only respond to key-down events (not key-up or repeat events)</li><li>We support both Enter and Space keys, following standard accessibility conventions</li><li>We toggle the checkbox state by calling the parent’s onChanged callback</li><li>We return KeyEventResult.handled to prevent the event from bubbling up</li><li>For unhandled keys, we return KeyEventResult.ignored to allow normal processing</li></ul><h3>7. Resource Cleanup</h3><pre>void _disposeFocusNode() {<br>  _focusNode.onKeyEvent = null;<br>  if (_isInternalFocusNode) {<br>    _focusNode.dispose();<br>  }<br>}<br><br>@override<br>void dispose() {<br>  _disposeFocusNode();<br>  super.dispose();<br>}</pre><p>Proper cleanup is crucial for preventing memory leaks:</p><ul><li>We remove the key event handler to break potential circular references</li><li>We only dispose of the focus nodes we created internally</li><li>The dispose() method ensures that cleanup happens when the widget is removed from the tree</li></ul><h3>8. Building the UI</h3><pre>@override<br>Widget build(BuildContext context) {<br>  return Checkbox(<br>    focusNode: _focusNode,<br>    value: widget.isChecked,<br>    onChanged: (isChecked) {<br>      widget.onChanged(isChecked ?? false);<br>    },<br>  );<br>}</pre><p>The build method is straightforward — we delegate to Flutter’s built-in Checkbox widget while providing our managed focus node and ensuring the callback always receives a boolean value.</p><h3>Usage Examples</h3><h3>Basic Usage</h3><pre>bool _isChecked = false;<br><br>FocusedCheckBox(<br>  isChecked: _isChecked,<br>  onChanged: (value) {<br>    setState(() {<br>      _isChecked = value;<br>    });<br>  },<br>)</pre><h3>Advanced Usage with Custom Focus Management</h3><pre>class MyForm extends StatefulWidget {<br>  @override<br>  _MyFormState createState() =&gt; _MyFormState();<br>}<br><br>class _MyFormState extends State&lt;MyForm&gt; {<br>  final FocusNode _checkboxFocus = FocusNode();<br>  bool _isChecked = false;<br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        TextField(<br>          onSubmitted: (_) =&gt; _checkboxFocus.requestFocus(),<br>        ),<br>        FocusedCheckBox(<br>          focusNode: _checkboxFocus,<br>          isChecked: _isChecked,<br>          onChanged: (value) {<br>            setState(() {<br>              _isChecked = value;<br>            });<br>          },<br>        ),<br>      ],<br>    );<br>  }<br>  @override<br>  void dispose() {<br>    _checkboxFocus.dispose();<br>    super.dispose();<br>  }<br>}</pre><h3>Demo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zWAPzbHz_O5XYcQA.gif" /></figure><h3>Key Benefits</h3><h3>Accessibility First</h3><p>This widget provides excellent keyboard navigation support, making your app accessible to users who navigate with keyboards, screen readers, or other assistive technologies.</p><h3>Flexible Focus Management</h3><p>By accepting an optional external focus node, the widget can participate in complex focus management scenarios while still working perfectly in simple cases.</p><h3>Memory Safe</h3><p>Proper resource management ensures no memory leaks, even in dynamic scenarios where focus nodes change frequently.</p><h3>Maintainable Code</h3><p>Clear separation of concerns and well-documented methods make this widget easy to understand, modify, and extend.</p><h3>Best Practices Demonstrated</h3><ol><li><strong>Controlled Components</strong>: The widget doesn’t maintain its own checked state — the parent controls it</li><li><strong>Resource Management</strong>: Proper disposal of created resources prevents memory leaks</li><li><strong>Accessibility</strong>: Support for standard keyboard interactions (Enter and Space)</li><li><strong>Flexibility</strong>: Optional parameters allow for both simple and complex use cases</li><li><strong>Defensive Programming</strong>: Null-safe operations and proper event handling</li></ol><h3>Conclusion</h3><p>Creating accessible, well-designed custom widgets in Flutter requires attention to focus management, keyboard interactions, and resource cleanup. This FocusedCheckBox widget demonstrates how to handle these concerns while maintaining clean, reusable code.</p><p>By following the patterns shown here, you can create other custom interactive widgets that provide excellent user experiences for all users, regardless of how they interact with your app. Remember, accessibility isn’t just about compliance — it’s about creating inclusive experiences that work well for everyone.</p><p><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@kiran.kulkarni_3903"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce891d3e140" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/building-a-keyboard-accessible-custom-checkbox-widget-in-flutter-fce891d3e140">Building a Keyboard-Accessible Custom Checkbox Widget in Flutter</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BLoC Testing with Mockito in Flutter]]></title>
            <link>https://blog.nonstopio.com/bloc-testing-with-mockito-in-flutter-22074a10b9d4?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/22074a10b9d4</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 05:28:47 GMT</pubDate>
            <atom:updated>2025-03-31T05:28:47.064Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with Flutter and BLoC for state management, it’s crucial to write robust tests to ensure your app behaves correctly. In this blog, we’ll walk through testing a Flutter BLoC using Mockito, focusing on a repository pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xR6NRQgXgJo4J9NeIwR6tA@2x.png" /></figure><h3>Steps Covered:</h3><ol><li>Define an abstract repository (ChallanRepo)</li><li>Implement the repository (ChallanRepoImpl)</li><li>Create a BLoC (ChallanBloc) to fetch a list of challans</li><li>Write unit tests using Mockito for the BLoC’s behavior</li></ol><h3>1️⃣ Define the Abstract Repository</h3><p>We start by creating an abstract class ChallanRepo, which declares the getChallanList() method.</p><pre>abstract class ChallanRepo {<br>  Future&lt;List&lt;String&gt;&gt; getChallanList();<br>}</pre><h3>2️⃣ Implement the Repository (ChallanRepoImpl)</h3><p>This class simulates an API call by returning a hardcoded list after a delay.</p><pre>class ChallanRepoImpl implements ChallanRepo {<br>  @override<br>  Future&lt;List&lt;String&gt;&gt; getChallanList() async {<br>    await Future.delayed(Duration(seconds: 1));<br>    return [&quot;Challan 101&quot;, &quot;Challan 102&quot;, &quot;Challan 103&quot;];<br>  }<br>}</pre><h3>3️⃣ Create the BLoC (ChallanBloc)</h3><p>The BLoC manages states and events related to fetching challan data.</p><h3>📌 Events</h3><pre>abstract class ChallanEvent {}<br>class GetChallanEvent extends ChallanEvent {}</pre><h3>📌 States</h3><pre>abstract class ChallanState {}<br>class ChallanListLoadingState extends ChallanState {}<br>class ChallanListEmptyState extends ChallanState {}<br>class ChallanListLoadedState extends ChallanState {<br>  final List&lt;String&gt; challanList;<br>  ChallanListLoadedState(this.challanList);<br>}<br>class ChallanListErrorState extends ChallanState {<br>  final String message;<br>  ChallanListErrorState(this.message);<br>}</pre><h3>📌 BLoC Implementation</h3><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>class ChallanBloc extends Bloc&lt;ChallanEvent, ChallanState&gt; {<br>  final ChallanRepo challanRepo;<br>ChallanBloc(this.challanRepo) : super(ChallanListLoadingState()) {<br>    on&lt;GetChallanEvent&gt;(_onGetChallanList);<br>  }<br>Future&lt;void&gt; _onGetChallanList(<br>      GetChallanEvent event, Emitter&lt;ChallanState&gt; emit) async {<br>    try {<br>      emit(ChallanListLoadingState());<br>      final challanList = await challanRepo.getChallanList();<br>      if (challanList.isEmpty) {<br>        emit(ChallanListEmptyState());<br>      } else {<br>        emit(ChallanListLoadedState(challanList));<br>      }<br>    } catch (e) {<br>      emit(ChallanListErrorState(&quot;Failed to fetch challans&quot;));<br>    }<br>  }<br>}</pre><h3>4️⃣ Writing Tests with Mockito</h3><h3>📌 Install Dependencies</h3><p>Add the necessary dependencies to pubspec.yaml:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: &lt;take latest version&gt;<br>  mockito: &lt;take latest version&gt;<br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  flutter_lints: &lt;take latest version&gt;<br>  build_runner: &lt;take latest version&gt;<br>  bloc_test: &lt;take latest version&gt;</pre><p>Run:</p><pre>flutter pub get</pre><h3>📌 Step 2: Generate Mock Class</h3><p>Create a test file: test/challan_bloc_test.dart and add:</p><pre>import &#39;package:mockito/annotations.dart&#39;;<br>import &#39;../lib/challan_repo.dart&#39;;<br>@GenerateMocks([ChallanRepo])<br>void main() {}</pre><p>Generate the mock class by running:</p><pre>flutter pub run build_runner build</pre><p>This creates test/challan_bloc_test.mocks.dart.</p><h3>📌 Step 3: Write the Test</h3><p>Create test/challan_bloc_test.dart and add the following:</p><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:mockito/mockito.dart&#39;;<br>import &#39;package:mockito/annotations.dart&#39;;<br>import &#39;package:bloc_test/bloc_test.dart&#39;;<br>import &#39;../lib/challan_repo.dart&#39;;<br>import &#39;../lib/challan_bloc.dart&#39;;<br>import &#39;challan_bloc_test.mocks.dart&#39;;<br>@GenerateMocks([ChallanRepo])<br>void main() {<br>  late ChallanBloc challanBloc;<br>  late MockChallanRepo mockChallanRepo;<br>  setUp(() {<br>    mockChallanRepo = MockChallanRepo();<br>    challanBloc = ChallanBloc(mockChallanRepo);<br>  });<br>  tearDown(() {<br>    challanBloc.close();<br>  });<br>  test(&quot;Initial state should be ChallanListLoadingState&quot;, () {<br>    expect(challanBloc.state, isA&lt;ChallanListLoadingState&gt;());<br>  });<br>  blocTest&lt;ChallanBloc, ChallanState&gt;(<br>    &quot;Should emit [ChallanListLoadingState, ChallanListLoadedState] when fetching challans successfully&quot;,<br>    build: () {<br>      when(mockChallanRepo.getChallanList()).thenAnswer(<br>          (_) async =&gt; [&quot;Challan 101&quot;, &quot;Challan 102&quot;, &quot;Challan 103&quot;]);<br>      return challanBloc;<br>    },<br>    act: (bloc) =&gt; bloc.add(GetChallanEvent()),<br>    expect: () =&gt; [<br>      ChallanListLoadingState(),<br>      ChallanListLoadedState([&quot;Challan 101&quot;, &quot;Challan 102&quot;, &quot;Challan 103&quot;]),<br>    ],<br>  );<br>  blocTest&lt;ChallanBloc, ChallanState&gt;(<br>    &quot;Should emit [ChallanListLoadingState, ChallanListEmptyState] when API returns an empty list&quot;,<br>    build: () {<br>      when(mockChallanRepo.getChallanList()).thenAnswer((_) async =&gt; []);<br>      return challanBloc;<br>    },<br>    act: (bloc) =&gt; bloc.add(GetChallanEvent()),<br>    expect: () =&gt; [ChallanListLoadingState(), ChallanListEmptyState()],<br>  );<br>  blocTest&lt;ChallanBloc, ChallanState&gt;(<br>    &quot;Should emit [ChallanListLoadingState, ChallanListErrorState] when API throws an error&quot;,<br>    build: () {<br>      when(mockChallanRepo.getChallanList()).thenThrow(Exception(&quot;API error&quot;));<br>      return challanBloc;<br>    },<br>    act: (bloc) =&gt; bloc.add(GetChallanEvent()),<br>    expect: () =&gt; [ChallanListLoadingState(), ChallanListErrorState(&quot;Failed to fetch challans&quot;)],<br>  );<br>}</pre><pre>🔥 Recap</pre><p>✔ Created ChallanRepo (abstract class) and ChallanRepoImpl (implementation).<br>✔ Implemented ChallanBloc with GetChallanEvent and state management.<br>✔ Used Mockito to test the BLoC’s behavior.<br>✔ Tested success, empty, and error cases using bloc_test.</p><p>By following this structured approach, you can ensure your Flutter BLoC is well-tested and functions correctly in different scenarios. Happy coding! 🚀</p><blockquote>Here to make the community stronger by sharing our knowledge. <a href="https://medium.com/@kiran.kulkarni_3903">Follow me</a> and <a href="https://medium.com/nonstopio">my team</a> to stay updated on the latest and greatest in the web &amp; mobile tech world.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22074a10b9d4" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/bloc-testing-with-mockito-in-flutter-22074a10b9d4">BLoC Testing with Mockito in Flutter</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Dependent Dropdowns with BLoC in Flutter]]></title>
            <link>https://blog.nonstopio.com/implementing-dependent-dropdowns-with-bloc-in-flutter-eff91db2f6cb?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/eff91db2f6cb</guid>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-web]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 11:51:40 GMT</pubDate>
            <atom:updated>2025-02-04T11:51:40.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Handling dependent dropdowns in Flutter using the BLoC pattern is a common scenario when implementing forms that require cascading selections. A typical example is selecting a country, then a state, and finally a city. In this guide, we will cover how to properly manage this scenario using BLoC events, states, and efficient state management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTsDqebrHdc0mrJqxBz3Jg.png" /></figure><h3>Requirements</h3><ul><li><a href="https://docs.flutter.dev/get-started/install">Flutter</a></li><li><a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a> package</li><li>API or mock data for countries, states, and cities</li></ul><h3>Step 1: Define BLoC Events</h3><p>To handle user interactions and API calls, we define different events for loading data and selecting values.</p><pre>abstract class DropdownEvent {}class LoadCountries extends DropdownEvent {}<br>class CountrySelected extends DropdownEvent {<br>  final String selectedCountry;<br>  CountrySelected(this.selectedCountry);<br>}class StateSelected extends DropdownEvent {<br>  final String selectedState;<br>  StateSelected(this.selectedState);<br>}class CitySelected extends DropdownEvent {<br>  final String selectedCity;<br>  CitySelected(this.selectedCity);<br>}class EditSelection extends DropdownEvent {<br>  final String selectedCountry;<br>  final String selectedState;<br>  final String selectedCity;<br>EditSelection(this.selectedCountry, this.selectedState, this.selectedCity);<br>}</pre><h3>Step 2: Define BLoC States</h3><p>We define states to hold the list of available options and selected values.</p><pre>abstract class DropdownState {}<br>class DropdownInitial extends DropdownState {}<br>class DropdownLoaded extends DropdownState {<br>  final List&lt;String&gt; countries;<br>  final List&lt;String&gt; states;<br>  final List&lt;String&gt; cities;<br>  final String? selectedCountry;<br>  final String? selectedState;<br>  final String? selectedCity;<br>  DropdownLoaded({<br>    required this.countries,<br>    required this.states,<br>    required this.cities,<br>    this.selectedCountry,<br>    this.selectedState,<br>    this.selectedCity,<br>  });<br>}</pre><h3>Step 3: Implement the BLoC</h3><p>The BLoC will handle fetching data, user selections, and emitting new states.</p><pre>class DropdownBloc extends Bloc&lt;DropdownEvent, DropdownState&gt; {<br>  DropdownBloc() : super(DropdownInitial()) {<br>    on&lt;LoadCountries&gt;(_loadCountries);<br>    on&lt;CountrySelected&gt;(_onCountrySelected);<br>    on&lt;StateSelected&gt;(_onStateSelected);<br>    on&lt;CitySelected&gt;(_onCitySelected);<br>    on&lt;EditSelection&gt;(_onEditSelection);<br>  }<br>Future&lt;void&gt; _loadCountries(LoadCountries event, Emitter&lt;DropdownState&gt; emit) async {<br>    final countries = await fetchCountries();<br>    emit(DropdownLoaded(countries: countries, states: [], cities: []));<br>  }<br>  Future&lt;void&gt; _onCountrySelected(CountrySelected event, Emitter&lt;DropdownState&gt; emit) async {<br>    final states = await fetchStates(event.selectedCountry);<br>    emit(DropdownLoaded(<br>      countries: (state as DropdownLoaded).countries,<br>      states: states,<br>      cities: [],<br>      selectedCountry: event.selectedCountry,<br>    ));<br>  }<br>  Future&lt;void&gt; _onStateSelected(StateSelected event, Emitter&lt;DropdownState&gt; emit) async {<br>    final cities = await fetchCities(event.selectedState);<br>    emit(DropdownLoaded(<br>      countries: (state as DropdownLoaded).countries,<br>      states: (state as DropdownLoaded).states,<br>      cities: cities,<br>      selectedCountry: (state as DropdownLoaded).selectedCountry,<br>      selectedState: event.selectedState,<br>    ));<br>  }<br>  void _onCitySelected(CitySelected event, Emitter&lt;DropdownState&gt; emit) {<br>    emit(DropdownLoaded(<br>      countries: (state as DropdownLoaded).countries,<br>      states: (state as DropdownLoaded).states,<br>      cities: (state as DropdownLoaded).cities,<br>      selectedCountry: (state as DropdownLoaded).selectedCountry,<br>      selectedState: (state as DropdownLoaded).selectedState,<br>      selectedCity: event.selectedCity,<br>    ));<br>  }<br>  Future&lt;void&gt; _onEditSelection(EditSelection event, Emitter&lt;DropdownState&gt; emit) async {<br>    final countries = await fetchCountries();<br>    final states = await fetchStates(event.selectedCountry);<br>    final cities = await fetchCities(event.selectedState);<br>    emit(DropdownLoaded(<br>      countries: countries,<br>      states: states,<br>      cities: cities,<br>      selectedCountry: event.selectedCountry,<br>      selectedState: event.selectedState,<br>      selectedCity: event.selectedCity,<br>    ));<br>  }<br>}</pre><h3>Step 4: Implement the UI</h3><p>Now, we create the UI that interacts with the BLoC.</p><pre>class DropdownPage extends StatelessWidget {<br>  final String? editCountry;<br>  final String? editState;<br>  final String? editCity;<br><br>DropdownPage({this.editCountry, this.editState, this.editCity});<br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (_) {<br>        final bloc = DropdownBloc();<br>        if (editCountry != null) {<br>          bloc.add(EditSelection(editCountry!, editState!, editCity!));<br>        } else {<br>          bloc.add(LoadCountries());<br>        }<br>        return bloc;<br>      },<br>      child: Column(<br>        children: [<br>          BlocBuilder&lt;DropdownBloc, DropdownState&gt;(<br>            builder: (context, state) {<br>              if (state is DropdownLoaded) {<br>                return DropdownButton&lt;String&gt;(<br>                  value: state.selectedCountry,<br>                  hint: Text(&quot;Select Country&quot;),<br>                  items: state.countries.map((country) =&gt; DropdownMenuItem(value: country, child: Text(country))).toList(),<br>                  onChanged: (value) =&gt; context.read&lt;DropdownBloc&gt;().add(CountrySelected(value!)),<br>                );<br>              }<br>              return CircularProgressIndicator();<br>            },<br>          ),<br>          BlocBuilder&lt;DropdownBloc, DropdownState&gt;(<br>            builder: (context, state) {<br>              if (state is DropdownLoaded &amp;&amp; state.selectedCountry != null) {<br>                return DropdownButton&lt;String&gt;(<br>                  value: state.selectedState,<br>                  hint: Text(&quot;Select State&quot;),<br>                  items: state.states.map((state) =&gt; DropdownMenuItem(value: state, child: Text(state))).toList(),<br>                  onChanged: (value) =&gt; context.read&lt;DropdownBloc&gt;().add(StateSelected(value!)),<br>                );<br>              }<br>              return SizedBox.shrink();<br>            },<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h3>Conclusion</h3><p>By implementing dependent dropdowns using BLoC, we ensure a clean architecture, efficient state management, and easy handling of prepopulated selections. This approach is scalable for larger applications and keeps the UI responsive.</p><p>Hope you enjoyed this article!</p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@kiran.kulkarni_3903"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eff91db2f6cb" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/implementing-dependent-dropdowns-with-bloc-in-flutter-eff91db2f6cb">Implementing Dependent Dropdowns with BLoC in Flutter</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</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 Convert JSON API Response to an Excel Sheet in Flutter Using the excel Package]]></title>
            <link>https://blog.nonstopio.com/how-to-convert-json-api-response-to-an-excel-sheet-in-flutter-using-the-excel-package-dd0b3e2784f5?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd0b3e2784f5</guid>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 05:39:40 GMT</pubDate>
            <atom:updated>2025-02-03T05:39:40.793Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of app development, you often encounter scenarios where you need to export data, such as reports or analytics, in a universally accepted format like Excel. In this blog, we’ll explore how to convert JSON responses from an API into an Excel sheet using the popular <a href="https://pub.dev/packages/excel">Excel package</a> in Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNzyw46bNDdW08g8vnzZdQ.png" /></figure><h3>Why Export Data to Excel?</h3><p>Excel is widely used for data analysis and sharing. By exporting your app’s data to Excel, you enable users to:</p><ol><li>Analyze data offline.</li><li>Share data seamlessly across platforms.</li><li>Present reports in a professional format.</li></ol><h3>Step-by-Step Implementation</h3><p>Here’s how you can convert a JSON API response into an Excel file:</p><h3>1. Add Dependencies</h3><p>Start by adding the excel package to your pubspec.yaml:</p><pre>dependencies:<br>  excel: ^4.0.6</pre><p>Run flutter pub get to fetch the package.</p><h3>2. Import Required Packages</h3><p>Add the necessary imports in your Dart file:</p><pre>import &#39;package:excel/excel.dart&#39;;<br>import &#39;dart:typed_data&#39;;<br>import &#39;dart:html&#39; as html; // For web-based downloads</pre><h3>3. Create the JSON to Excel Conversion Method</h3><p>Below is a generic function to convert a JSON list to an Excel sheet and download it:</p><pre>Future&lt;void&gt; downloadExcelGeneric({<br>  required List&lt;Map&lt;String, dynamic&gt;&gt; jsonData,<br>  required String fileName,<br>}) async {<br>  try {<br>    // Step 1: Create an Excel object<br>    var excel = Excel.createExcel();// Step 2: Add a sheet<br>    String sheetName = &quot;Sheet1&quot;;<br>    Sheet sheet = excel[sheetName];<br>// Step 3: Add headers (keys from the first map in the JSON list)<br>    if (jsonData.isNotEmpty) {<br>      var headers = jsonData.first.keys.toList();<br>      sheet.appendRow(headers.map((header) =&gt; TextCellValue(header)).toList());<br>---<br><br>// Step 4: Add data rows<br>      for (var item in jsonData) {<br>        sheet.appendRow(headers.map((key) =&gt; TextCellValue(item[key].toString())).toList());<br>      }<br>    }<br>    // Step 5: Save the Excel file as bytes<br>    Uint8List excelBytes = Uint8List.fromList(excel.save()!);<br>    // Step 6: Create a Blob and URL for downloading the file<br>    final blob = html.Blob([excelBytes],<br>        &#39;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#39;);<br>    final url = html.Url.createObjectUrlFromBlob(blob);<br>    final defaultFileName =<br>        &#39;${fileName}_Details_${DateTime.now().toIso8601String()}.xlsx&#39;;<br>    // Step 7: Create a download link<br>    html.AnchorElement(href: url)<br>      ..target = &#39;blank&#39;<br>      ..download = defaultFileName<br>      ..click();<br>    // Step 8: Clean up<br>    html.Url.revokeObjectUrl(url);<br>  } catch (e) {<br>    // Handle errors gracefully<br>    print(&quot;Error while exporting to Excel: $e&quot;);<br>    rethrow;<br>  }<br>}<br></pre><h3>3. Example Usage</h3><p>To use the function, simply call it with your JSON data and desired file name:</p><pre>void exportToExcel() {<br>  List&lt;Map&lt;String, dynamic&gt;&gt; jsonResponse = [<br>    {&quot;Name&quot;: &quot;John Doe&quot;, &quot;Age&quot;: 30, &quot;Role&quot;: &quot;Developer&quot;},<br>    {&quot;Name&quot;: &quot;Jane Smith&quot;, &quot;Age&quot;: 25, &quot;Role&quot;: &quot;Designer&quot;},<br>    {&quot;Name&quot;: &quot;Sam Brown&quot;, &quot;Age&quot;: 35, &quot;Role&quot;: &quot;Manager&quot;},<br>  ];<br>downloadExcelGeneric(<br>    jsonData: jsonResponse,<br>    fileName: &quot;Employee_Data&quot;,<br>  );<br>}</pre><p>This will generate an Excel file with the given data and allow the user to download it.</p><h3>5. Key Features of the excel Package</h3><ul><li><strong>Ease of Use</strong>: Create, modify, and save Excel files effortlessly.</li><li><strong>Sheet Management</strong>: Work with multiple sheets in a workbook.</li><li><strong>Cell Styling</strong>: Customize font styles, colors, and borders (if needed).</li><li><strong>Compatibility</strong>: Supports .xlsx format for universal access.</li></ul><h3>Best Practices</h3><ol><li><strong>Validate Data</strong>: Ensure the JSON data is well-formed before processing.</li><li><strong>Handle Errors</strong>: Catch exceptions and provide user-friendly error messages.</li><li><strong>Dynamic Headers</strong>: Use the keys from the first JSON object to dynamically create headers.</li><li><strong>Responsive Naming</strong>: Generate file names dynamically with timestamps to avoid overwriting.</li></ol><h3>Final Output</h3><p>When the function is executed, users can download an Excel file containing the structured data from the JSON response. The file will have headers derived from the JSON keys and rows corresponding to the data values.</p><h3>Conclusion</h3><p>Exporting JSON data to Excel is a valuable feature for many applications. The excel package makes this process straightforward in Flutter, providing users with a powerful tool for offline analysis and sharing.</p><p>Start integrating this functionality into your app today, and give your users the convenience of exporting their data to Excel with ease!</p><p>Hope you enjoyed this article!</p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@kiran.kulkarni_3903"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd0b3e2784f5" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/how-to-convert-json-api-response-to-an-excel-sheet-in-flutter-using-the-excel-package-dd0b3e2784f5">How to Convert JSON API Response to an Excel Sheet in Flutter Using the excel Package</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Enums as Default Values in Dart]]></title>
            <link>https://blog.nonstopio.com/leveraging-enums-as-default-values-in-dart-6dfd9297a13a?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dfd9297a13a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[class]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 05:36:55 GMT</pubDate>
            <atom:updated>2025-02-03T05:36:55.815Z</atom:updated>
            <content:encoded><![CDATA[<p>Enums in Dart are an excellent way to define a fixed set of values with associated properties. A common requirement is to use an enum value as a default in your class while accessing its properties dynamically. Here&#39;s how you can achieve this effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxAZKnjOwMeya9sTVRObIA.png" /></figure><h3>The Problem</h3><p>Suppose you have an enum like this:</p><pre>enum TrackBy {<br>  byConsignment(name: &#39;Search by Consignment&#39;),<br>  byShipment(name: &#39;Search by Shipment&#39;),<br>  byBag(name: &#39;Search by Bag&#39;);<br><br>const TrackBy({<br>    required this.name,<br>  });<br><br> final String name;<br>}</pre><p>You want to use TrackBy.byConsignment as the default for a class field and still access the associated name property at runtime.</p><h3>The Solution</h3><p>Instead of storing just the property value (like name), store the entire enum value in your class and access its properties dynamically. Here&#39;s the complete implementation:</p><pre>class TrackByModel {<br>  final TrackBy trackBy; // Store the enum value itself<br>  final int limit;<br>const TrackByModel({<br>    this.trackBy = TrackBy.byConsignment, // Enum as default<br>    this.limit = 50,<br>  });<br>String get name =&gt; trackBy.name; // Access the name at runtime<br>}</pre><h3>How It Works</h3><ol><li><strong>Storing the Enum</strong>: The trackBy field holds the entire TrackBy enum value, not just its name property.</li><li><strong>Default Value</strong>: The trackBy field defaults to TrackBy.byConsignment.</li><li><strong>Dynamic Access</strong>: The name getter dynamically retrieves the name property of the stored enum value.</li></ol><h3>Benefits</h3><ul><li><strong>Clean Design</strong>: The TrackByModel class directly works with TrackBy values, keeping the logic simple and intuitive.</li><li><strong>Flexibility</strong>: Changing the default value is straightforward and localized.</li><li><strong>Dynamic Property Access</strong>: The name getter ensures you always get the associated property of the enum, making the code more maintainable.</li></ul><h3>Example Usage</h3><p>Here’s how you can use this design:</p><pre>void main() {<br>  // Default usage<br>  const model = TrackByModel();<br>  print(&#39;Default track by: ${model.name}, Limit: ${model.limit}&#39;);<br>// Custom usage<br>  const customModel = TrackByModel(trackBy: TrackBy.byShipment, limit: 100);<br>  print(&#39;Custom track by: ${customModel.name}, Limit: ${customModel.limit}&#39;);<br>}</pre><p><strong>Output</strong>:</p><pre>Default track by: Search by Consignment, Limit: 50<br>Custom track by: Search by Shipment, Limit: 100</pre><h3>Conclusion</h3><p>By storing the enum value in the class and accessing its properties dynamically, you gain both flexibility and clarity in your Dart code. This approach is especially useful in scenarios where you need to manage associated data for enums efficiently.</p><p>Hope you enjoyed this article!</p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@kiran.kulkarni_3903"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dfd9297a13a" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/leveraging-enums-as-default-values-in-dart-6dfd9297a13a">Leveraging Enums as Default Values in Dart</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Dialog That Dismisses on Browser’s Back Button in Flutter Web Using go_router]]></title>
            <link>https://blog.nonstopio.com/creating-a-dialog-that-dismisses-on-browsers-back-button-in-flutter-web-using-go-router-235184ebb667?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/235184ebb667</guid>
            <category><![CDATA[dialog]]></category>
            <category><![CDATA[back-button]]></category>
            <category><![CDATA[go-router]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[flutter-web]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 05:23:05 GMT</pubDate>
            <atom:updated>2025-02-03T05:23:05.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Handling dialogs in Flutter Web can be tricky, especially when dealing with browser navigation. By default, when a user presses the browser back button while a dialog is open, Flutter’s go_router navigates back to the previous page instead of dismissing the dialog. This is a known issue (<a href="https://github.com/flutter/flutter/issues/112765">Flutter Issue #112765</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-NpcDT9PGiBlIXlVX3KlA.png" /></figure><p>In this article, we’ll explore a workaround inspired by <a href="https://github.com/flutter/flutter/issues/112765#issuecomment-1872521794">this GitHub comment</a> to handle dialogs correctly when pressing the browser back button.</p><h3>The Issue</h3><p>Consider the following scenario:</p><ul><li>Open the Flutter web app in a new browser tab.</li><li>Press a button that opens a dialog.</li><li>Press the browser “Back” button.</li><li>Instead of closing the dialog, the entire application navigates back, often closing the tab.</li></ul><h3>Expected Behavior:</h3><p>The dialog should close, but the application should remain open on the same page.</p><h3>Solution: Using DialogPage as a Custom Route</h3><p>To fix this, we create a custom DialogPage class that extends Page&lt;T&gt;. This allows us to handle the dialog as a route withingo_router, ensuring it behaves like a proper navigation event.</p><h3>Implementing DialogPage</h3><pre>class DialogPage&lt;T&gt; extends Page&lt;T&gt; {<br>  final Offset? anchorPoint;<br>  final Color? barrierColor;<br>  final bool barrierDismissible;<br>  final String? barrierLabel;<br>  final bool useSafeArea;<br>  final CapturedThemes? themes;<br>  final WidgetBuilder builder;<br>  final EdgeInsetsGeometry? contentPadding; // Padding inside the dialog<br>  final double? width; // Width constraint<br>  final double? height; // Height constraint<br>  final BorderRadiusGeometry? borderRadius; // Rounded corners<br><br>const DialogPage({<br>    required this.builder,<br>    this.anchorPoint,<br>    this.barrierColor = Colors.black54,<br>    this.barrierDismissible = true,<br>    this.barrierLabel,<br>    this.useSafeArea = true,<br>    this.themes,<br>    this.contentPadding,<br>    this.width,<br>    this.height,<br>    this.borderRadius,<br>    super.key,<br>    super.name,<br>    super.arguments,<br>    super.restorationId,<br>  });<br><br>@override<br>  Route&lt;T&gt; createRoute(BuildContext context) =&gt; DialogRoute&lt;T&gt;(<br>        context: context,<br>        settings: this,<br>        builder: (context) =&gt; Dialog(<br>          backgroundColor: Colors.white,<br>          elevation: 24,<br>          shape: RoundedRectangleBorder(<br>            borderRadius: borderRadius ?? BorderRadius.circular(16.0),<br>          ),<br>          child: SizedBox(<br>            width: width ?? context.width * 0.8,<br>            height: height ?? context.height * 0.8,<br>            child: builder(context),<br>          ),<br>        ),<br>        anchorPoint: anchorPoint,<br>        barrierColor: barrierColor,<br>        barrierDismissible: barrierDismissible,<br>        barrierLabel: barrierLabel,<br>        useSafeArea: useSafeArea,<br>        themes: themes,<br>      );<br>}</pre><h3>Adding Dialog as a Route in go_router</h3><p>We define a route for the dialog inside go_router:</p><pre>GoRoute(<br>  path: &#39;/dashboard/circular&#39;,<br>  builder: (context, state) =&gt; const Circular(),<br>  routes: [<br>    // Dialog route<br>    GoRoute(<br>      path: &#39;/dialog&#39;,<br>      pageBuilder: (context, state) =&gt; DialogPage(<br>        width: context.width * 0.3,<br>        height: context.height * 0.3,<br>        builder: (context) =&gt; const DialogAsARoute(),<br>      ),<br>    )<br>  ],<br>),</pre><h3>How This Works</h3><ul><li>The DialogPage ensures that the dialog behaves like a real navigation event.</li><li>Pressing the browser back button will now dismiss the dialog instead of navigating away.</li><li>The application remains open in the same state.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uqrN7Di0Q8HcbP6D8FgeBw.gif" /><figcaption>Sample Program with Dialog on Route with GoRouter</figcaption></figure><h3>Conclusion</h3><p>While this solution is not a perfect fix, it provides a much-needed improvement over the default behavior of go_router in Flutter Web.</p><p>You can find the full implementation in this <a href="https://github.com/kirannonstop/go_router_breadcrums/blob/main/lib/dialog_as_page.dart">GitHub repository</a>.</p><p>Hope you enjoyed this article!</p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@kiran.kulkarni_3903"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235184ebb667" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/creating-a-dialog-that-dismisses-on-browsers-back-button-in-flutter-web-using-go-router-235184ebb667">Creating a Dialog That Dismisses on Browser’s Back Button in Flutter Web Using go_router</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Breadcrumbs in Flutter Using GoRouter: A Step-by-Step Guide]]></title>
            <link>https://blog.nonstopio.com/creating-breadcrumbs-in-flutter-using-gorouter-a-step-by-step-guide-cce006757266?source=rss-44bbbaee7cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/cce006757266</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[breadcrumbs]]></category>
            <category><![CDATA[go-router]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Kiran Kulkarni]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 12:01:29 GMT</pubDate>
            <atom:updated>2024-12-16T12:01:29.533Z</atom:updated>
            <content:encoded><![CDATA[<p>Breadcrumbs are an essential UI element for enhancing app navigation, especially for hierarchical or multi-level applications. This blog demonstrates creating breadcrumbs in a Flutter app using the GoRouter package. Additionally, it will showcase a complete navigation system that adapts to mobile and web layouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELkfcac89_ZcJ_FPSnuuig@2x.png" /></figure><h3>What We’ll Build</h3><p>We’ll create a Flutter app with the following:</p><ol><li><strong>Navigation Drawer</strong>: For smaller screens (mobile).</li><li><strong>Sidebar Navigation</strong>: For larger screens (web).</li><li><strong>Breadcrumbs</strong>: To display the current navigation path and allow users to navigate back to previous levels.</li></ol><h3>Step 1: Setting Up the Project</h3><p>First, create a new Flutter project and add the go_router package to the pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  go_router: ^14.6.2</pre><p>Install the package by running:</p><pre>flutter pub get</pre><h3>Step 2: Define Pages</h3><p>Define the main screens for the app. Each screen will have basic content and a Scaffold for consistency. Below are the screen implementations:</p><h4>DashboardPage</h4><pre>import &#39;package:flutter/material.dart&#39;;<br>class DashboardPage extends StatelessWidget {<br>  const DashboardPage({super.key});<br>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;Dashboard&quot;)),<br>      body: const Center(child: Text(&quot;Dashboard Content&quot;)),<br>    );<br>  }<br>}</pre><h4>Homework Page</h4><pre>import &#39;package:flutter/material.dart&#39;;<br>class Homework extends StatelessWidget {<br>  const Homework({super.key});<br>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;Homework&quot;)),<br>      body: const Center(child: Text(&quot;Homework Content&quot;)),<br>    );<br>  }<br>}</pre><p>Similarly, create the <strong>Message</strong>, <strong>Circular</strong>, and <strong>ContactUs</strong> pages.</p><h3>Step 3: Create the App Layout</h3><p>The AppLayout widget serves as a container for the app’s structure. It supports:</p><ul><li><strong>Drawer navigation</strong> for mobile devices.</li><li><strong>Sidebar navigation</strong> for web layouts.</li></ul><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:go_router/go_router.dart&#39;;<br>class AppLayout extends StatelessWidget {<br>  final Widget child;<br>const AppLayout({super.key, required this.child});<br>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;My App&quot;)),<br>      drawer: MediaQuery.of(context).size.width &lt; 600<br>          ? Drawer(<br>              child: NavigationMenu(<br>                onTap: (route) =&gt; context.go(route),<br>              ),<br>            )<br>          : null,<br>      body: Row(<br>        children: [<br>          if (MediaQuery.of(context).size.width &gt;= 600)<br>            SizedBox(<br>              width: 200,<br>              child: NavigationMenu(<br>                onTap: (route) =&gt; context.go(route),<br>              ),<br>            ),<br>          Expanded(<br>            child: Column(<br>              crossAxisAlignment: CrossAxisAlignment.start,<br>              children: [<br>                if (MediaQuery.of(context).size.width &gt;= 600) const Breadcrumbs(),<br>                Expanded(child: child),<br>              ],<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h3>Step 4: Build the Navigation Menu</h3><p>The NavigationMenu widget is a reusable menu that supports:</p><ul><li>Collapsible submenus for items like “Dashboard.”</li><li>Drawer closing behavior on mobile.</li></ul><pre>class NavigationMenu extends StatefulWidget {<br>  final Function(String route) onTap;<br>const NavigationMenu({super.key, required this.onTap});<br>@override<br>  State&lt;NavigationMenu&gt; createState() =&gt; _NavigationMenuState();<br>}<br>class _NavigationMenuState extends State&lt;NavigationMenu&gt; {<br>  bool isDashboardExpanded = false;<br>@override<br>  Widget build(BuildContext context) {<br>    return ListView(<br>      children: [<br>        ListTile(<br>          title: const Text(&quot;Dashboard&quot;),<br>          trailing: Icon(isDashboardExpanded ? Icons.expand_less : Icons.expand_more),<br>          onTap: () {<br>            setState(() {<br>              isDashboardExpanded = !isDashboardExpanded;<br>            });<br>          },<br>        ),<br>        if (isDashboardExpanded) ...[<br>          _buildSubmenuItem(&quot;Homework&quot;, &quot;/dashboard/homework&quot;),<br>          _buildSubmenuItem(&quot;Messages&quot;, &quot;/dashboard/messages&quot;),<br>          _buildSubmenuItem(&quot;Circular&quot;, &quot;/dashboard/circular&quot;),<br>        ],<br>        const Divider(),<br>        ListTile(<br>          title: const Text(&quot;Contact Us&quot;),<br>          onTap: () {<br>            widget.onTap(&#39;/contactus&#39;);<br>            _closeDrawer(context);<br>          },<br>        ),<br>      ],<br>    );<br>  }<br>Widget _buildSubmenuItem(String title, String route) {<br>    return ListTile(<br>      title: Padding(<br>        padding: const EdgeInsets.only(left: 16.0),<br>        child: Text(title),<br>      ),<br>      onTap: () {<br>        widget.onTap(route);<br>        _closeDrawer(context);<br>      },<br>    );<br>  }<br>void _closeDrawer(BuildContext context) {<br>    if (MediaQuery.of(context).size.width &lt; 600) {<br>      Navigator.of(context).pop();<br>    }<br>  }<br>}</pre><h3>Step 5: Add Breadcrumbs</h3><p>The Breadcrumbs widget dynamically displays the current path and allows navigation to previous levels:</p><pre>class Breadcrumbs extends StatelessWidget {<br>  const Breadcrumbs({super.key});<br>@override<br>  Widget build(BuildContext context) {<br>    final currentLocation = GoRouter.of(context).routerDelegate.currentConfiguration.fullPath;<br>    final segments = currentLocation.split(&#39;/&#39;).where((s) =&gt; s.isNotEmpty).toList();<br>return Padding(<br>      padding: const EdgeInsets.all(8.0),<br>      child: Wrap(<br>        spacing: 8.0,<br>        children: [<br>          if (segments.isNotEmpty &amp;&amp; segments.first == &#39;dashboard&#39;) ...[<br>            InkWell(<br>              onTap: () =&gt; context.go(&#39;/&#39;),<br>              child: const Text(<br>                &#39;Dashboard&#39;,<br>                style: TextStyle(color: Colors.blue),<br>              ),<br>            ),<br>          ],<br>          for (int i = 1; i &lt; segments.length; i++) ...[<br>            const Text(&#39; &gt; &#39;),<br>            InkWell(<br>              onTap: () {<br>                final path = &#39;/&#39; + segments.sublist(0, i + 1).join(&#39;/&#39;);<br>                context.go(path);<br>              },<br>              child: Text(<br>                segments[i].capitalize(),<br>                style: const TextStyle(color: Colors.blue),<br>              ),<br>            ),<br>          ],<br>        ],<br>      ),<br>    );<br>  }<br>}<br><br>extension StringExtension on String {<br>  String capitalize() =&gt; &#39;${this[0].toUpperCase()}${substring(1)}&#39;;</pre><h3>Step 6: Define Routes Using GoRouter</h3><p>Now define the routes for the application using GoRouter.</p><pre>final GoRouter router = GoRouter(<br>  routes: [<br>    ShellRoute(<br>      builder: (context, state, child) =&gt; AppLayout(child: child),<br>      routes: [<br>        GoRoute(<br>          path: &#39;/&#39;,<br>          builder: (context, state) =&gt; const DashboardPage(),<br>        ),<br>        GoRoute(<br>          path: &#39;/dashboard/homework&#39;,<br>          builder: (context, state) =&gt; const Homework(),<br>        ),<br>        GoRoute(<br>          path: &#39;/dashboard/messages&#39;,<br>          builder: (context, state) =&gt; const Message(),<br>        ),<br>        GoRoute(<br>          path: &#39;/dashboard/circular&#39;,<br>          builder: (context, state) =&gt; const Circular(),<br>        ),<br>      ],<br>    ),<br>    GoRoute(<br>      path: &#39;/contactus&#39;,<br>      builder: (context, state) =&gt; const AppLayout(child: ContactUs()),<br>    ),<br>  ],<br>);</pre><h3>Step 7: Run the Application</h3><p>Finally, configure the MaterialApp.router to use the GoRouter.</p><pre>void main() {<br>  runApp(const MyApp());<br>}<br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>@override<br>  Widget build(BuildContext context) {<br>    return MaterialApp.router(<br>      debugShowCheckedModeBanner: false,<br>      routerConfig: router,<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4ada37UF_IT5K8TTexSjnw.gif" /></figure><h3>Conclusion</h3><p>In this blog, we built a Flutter app with breadcrumbs and responsive navigation using GoRouter. The complete code is available on <a href="https://github.com/kirannonstop/go_router_breadcrums">GitHub</a>. Clone it to explore further!</p><p>Hope you enjoyed this article!</p><blockquote><em>Here to make the community stronger by sharing our knowledge. </em><a href="https://medium.com/@kiran.kulkarni_3903"><em>Follow me</em></a><em> and </em><a href="https://medium.com/nonstopio"><em>my team</em></a><em> to stay updated on the latest and greatest in the web &amp; mobile tech world.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cce006757266" width="1" height="1" alt=""><hr><p><a href="https://blog.nonstopio.com/creating-breadcrumbs-in-flutter-using-gorouter-a-step-by-step-guide-cce006757266">Creating Breadcrumbs in Flutter Using GoRouter: A Step-by-Step Guide</a> was originally published in <a href="https://blog.nonstopio.com/">nonstopio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>