<?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 Pankaj Ram on Medium]]></title>
        <description><![CDATA[Stories by Pankaj Ram on Medium]]></description>
        <link>https://medium.com/@pankajram1101?source=rss-dd2152474d41------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y3sDiwOtPVswgQ1Ne-Qe4g.jpeg</url>
            <title>Stories by Pankaj Ram on Medium</title>
            <link>https://medium.com/@pankajram1101?source=rss-dd2152474d41------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:10:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pankajram1101/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[Dependency Injection in Flutter: Build Scalable, Maintainable, and Testable Apps]]></title>
            <link>https://medium.com/@pankajram1101/dependency-injection-in-flutter-build-scalable-maintainable-and-testable-apps-ed72c1ad2b91?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed72c1ad2b91</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 06:18:25 GMT</pubDate>
            <atom:updated>2026-10-23T06:18:25.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4k6rfANRlJK6K8rAoAqcg.png" /></figure><p>When building Flutter applications, we often focus on UI, state management, API integration, and navigation.</p><p>But as an application grows, one question becomes increasingly important:</p><p><strong>Who is responsible for creating the objects my application depends on?</strong></p><p>This is where <strong>Dependency Injection (DI)</strong> becomes useful.</p><p>In this article, we’ll understand Dependency Injection in Flutter with a practical example using:</p><ul><li>ChangeNotifier</li><li>Repository Pattern</li><li>Abstract classes</li><li>Real API implementation</li><li>Mock API implementation</li><li>Constructor injection</li></ul><h3>What is Dependency Injection?</h3><p>Dependency Injection means:</p><blockquote><strong><em>A class receives the objects it needs from outside instead of creating those objects itself.</em></strong></blockquote><p>Consider this example:</p><pre>class ProductRepository {<br>  final RealProductApi api = RealProductApi();<br><br>  Future&lt;ProductModel&gt; getProducts() {<br>    return api.getProducts();<br>  }<br>}</pre><p>At first, this looks perfectly fine.</p><p>But there is a problem.</p><p>ProductRepository is tightly coupled to RealProductApi.</p><p>What if we want to test the repository using dummy data?</p><p>What if the backend is unavailable?</p><p>What if we want to use a mock API during development?</p><p>We would have to modify the repository.</p><p>That’s exactly the problem Dependency Injection helps solve.</p><h3>The Problem with Hardcoded Dependencies</h3><p>Imagine our application has this structure:</p><pre>ProductScreen<br>      ↓<br>ProductProvider<br>      ↓<br>ProductRepository<br>      ↓<br>RealProductApi<br>      ↓<br>Backend</pre><p>If ProductRepository creates RealProductApi internally, the repository decides which API implementation it will use.</p><p>That makes the code harder to test and harder to change.</p><p>Instead, we can tell the repository:</p><blockquote><em>“I don’t care which API implementation you use. Just give me something that follows the </em><em>ApiService contract.&quot;</em></blockquote><h3>Step 1: Create an Abstraction</h3><p>Let’s create an abstract API service:</p><pre>abstract class ApiService {<br>  Future&lt;ProductModel&gt; getProduct({<br>    int page = 1,<br>    int limit = 10,<br>  });<br>}</pre><p>Now ProductRepository doesn&#39;t need to know about any specific API implementation.</p><p>It only knows about ApiService.</p><h3>Step 2: Create the Real API</h3><p>Our real implementation can call the backend:</p><p>class RealProductApi implements ApiService {<br> @override<br>Future&lt;ProductModel&gt; getProduct() async {<br> final response = await http.get(<br> Uri.parse(‘<a href="https://dummyjson.com/products">https://dummyjson.com/products</a>&#39;),<br>);</p><pre>if (response.statusCode == 200) {<br>  final responseData = json.decode(response.body);<br><br>  return ProductModel.fromJson(responseData);<br> }<br>  throw Exception(&#39;Failed to load products&#39;);<br> }<br>}</pre><p>This implementation communicates with the actual backend.</p><h3>Step 3: Create a Mock API</h3><p>Now let’s create another implementation:</p><pre>class MockProductApi implements ApiService {<br>  @override<br>  Future&lt;ProductModel&gt; getProduct({<br>    int page = 1,<br>    int limit = 10,<br>  }) async {<br>    return ProductModel();<br>  }<br>}</pre><p>This implementation doesn’t call the network.</p><p>It returns dummy data.</p><p>Now we have:</p><pre>             ApiService<br>                 │<br>        ┌────────┴────────┐<br>        ↓                 ↓<br>RealProductApi      MockProductApi<br>        ↓                 ↓<br>   Real Backend       Dummy Data</pre><p>Both implementations follow the same contract.</p><h3>Step 4: Inject the Dependency into the Repository</h3><p>Now comes the important part.</p><p>Instead of creating RealProductApi inside the repository:</p><pre>class ProductRepository {<br>  final ApiService apiService;<br><br>  ProductRepository(this.apiService);<br>  Future&lt;ProductModel&gt; getProduct({<br>    int page = 1,<br>    int limit = 10,<br>  }) {<br>    return apiService.getProduct(<br>      page: page,<br>      limit: limit,<br>    );<br>  }<br>}</pre><p>Notice this:</p><pre>ProductRepository(this.apiService);</pre><p>The repository receives its dependency from outside.</p><p>This is <strong>Constructor Injection</strong>.</p><p>The repository doesn’t know whether it received:</p><pre>RealProductApi()</pre><p>or:</p><pre>MockProductApi()</pre><p>It only knows that it received an ApiService.</p><h3>Step 5: Inject the Repository into the Provider</h3><p>We can apply the same principle to our ProductProvider:</p><pre>class ProductProvider extends ChangeNotifier {<br>  final ProductRepository productRepository;<br>ProductProvider({<br>    required this.productRepository,<br>  });<br>}</pre><p>Again, the provider doesn’t create the repository itself.</p><p>It receives it from outside.</p><p>Now our dependency graph looks like this:</p><pre>ProductScreen<br>      ↓<br>ProductProvider<br>      ↓<br>ProductRepository<br>      ↓<br>   ApiService<br>      ↓<br> ┌────┴─────┐<br> ↓          ↓<br>Real       Mock<br>API        API</pre><p>This is a simple but powerful architecture.</p><h3>Using it with Provider</h3><p>Now we can assemble everything:</p><pre>ChangeNotifierProvider(<br>  create: (context) =&gt; ProductProvider(<br>    productRepository: ProductRepository(<br>      RealProductApi(),<br>    ),<br>  ),<br>  child: const ProductScreen(),<br>)</pre><p>Here:</p><pre>RealProductApi<br>      ↓<br>ProductRepository<br>      ↓<br>ProductProvider<br>      ↓<br>ProductScreen</pre><p>Everything is injected from the outside.</p><h3>What About Mock API?</h3><p>This is where DI becomes really useful.</p><p>For testing, we can simply replace:</p><pre>RealProductApi()</pre><p>with:</p><pre>MockProductApi()<br><br>ChangeNotifierProvider(<br>  create: (context) =&gt; ProductProvider(<br>    productRepository: ProductRepository(<br>      MockProductApi(),<br>    ),<br>  ),<br>  child: const ProductScreen(),<br>)</pre><p>We didn’t modify:</p><ul><li>ProductProvider</li><li>ProductRepository</li><li>ProductScreen</li></ul><p>Only the implementation being injected changed.</p><p>That’s one of the biggest advantages of Dependency Injection.</p><h3>Environment-Based API Switching</h3><p>We can take this one step further.</p><p>Suppose we want to run our application using:</p><pre>Mock API<br>Real API<br>QA API<br>Production API</pre><p>We can use environment configuration.</p><p>For example:</p><pre>class AppConfig {<br>  static const String apiMode = String.fromEnvironment(<br>    &#39;API_MODE&#39;,<br>    defaultValue: &#39;real&#39;,<br>  );</pre><pre>  static bool get isMock =&gt; apiMode == &#39;mock&#39;;<br>}</pre><p>Then:</p><pre>final apiService = AppConfig.isMock<br>    ? MockProductApi()<br>    : RealProductApi();</pre><p>And inject it:</p><pre>ChangeNotifierProvider(<br>  create: (_) =&gt; ProductProvider(<br>    productRepository: ProductRepository(<br>      apiService,<br>    ),<br>  ),<br>  child: const ProductScreen(),<br>)</pre><p>Now we can run:</p><pre>flutter run --dart-define=API_MODE=mock</pre><p>or:</p><pre>flutter run --dart-define=API_MODE=real</pre><p>The application can use a different API implementation depending on how it was launched.</p><h3>Why Is This Better?</h3><p>Without DI:</p><pre>ProductRepository<br>       ↓<br>creates RealProductApi</pre><p>With DI:</p><pre>Dependency Injection<br>                     ↓<br>              ProductRepository<br>                     ↓<br>                 ApiService<br>                 /        \<br>                /          \<br>        RealProductApi   MockProductApi</pre><p>The repository is now loosely coupled to the implementation.</p><p>This gives us several benefits.</p><h3>1. Easier Testing</h3><p>We can inject a mock implementation instead of making real network requests.</p><h3>2. Loose Coupling</h3><p>The repository depends on an abstraction rather than a concrete implementation.</p><h3>3. Easier Maintenance</h3><p>Changing the API implementation doesn’t require changing the repository.</p><h3>4. Better Flexibility</h3><p>We can switch between real, mock, QA, or other implementations.</p><h3>5. Cleaner Architecture</h3><p>Responsibilities are separated.</p><h3>DI Is Not Just About Mocking</h3><p>It’s important to understand that Dependency Injection isn’t a “mock API technique.”</p><p>Mocking is just one benefit.</p><p>DI can be used for:</p><pre>API Services<br>Repositories<br>Database<br>Analytics<br>Logging<br>Authentication<br>Storage<br>Notifications<br>Location Services<br>Payment Services</pre><p>For example:</p><pre>class UserRepository {<br>  final ApiService apiService;<br>  final LocalDatabase database;<br>  final AnalyticsService analytics;<br><br>UserRepository(<br>    this.apiService,<br>    this.database,<br>    this.analytics,<br>  );<br>}</pre><p>All dependencies can be supplied from outside.</p><h3>Constructor Injection</h3><p>The approach we’ve used is called <strong>Constructor Injection</strong>.</p><pre>class ProductRepository {<br>  final ApiService apiService;<br>  ProductRepository(this.apiService);<br>}</pre><p>This is generally one of the simplest and clearest forms of DI in Flutter.</p><p>Other DI approaches exist, such as:</p><ul><li>Property injection</li><li>Method injection</li><li>Service Locator</li></ul><p>But constructor injection is an excellent starting point because the dependency is explicit and the class cannot easily exist without it.</p><h3>DI and Riverpod</h3><p>If you’re using Riverpod, providers can also act as a dependency injection mechanism.</p><p>For example:</p><pre>final apiServiceProvider = Provider&lt;ApiService&gt;((ref) {<br>  return RealProductApi();<br>});</pre><p>Then:</p><pre>final productRepositoryProvider =<br>    Provider&lt;ProductRepository&gt;((ref) {<br>  final apiService = ref.watch(apiServiceProvider);<br>  return ProductRepository(apiService);<br>});</pre><p>Now Riverpod manages the dependency graph.</p><p>Conceptually:</p><pre>Riverpod<br>   ↓<br>ApiService<br>   ↓<br>ProductRepository<br>   ↓<br>ProductProvider / Notifier<br>   ↓<br>UI</pre><p>This becomes particularly useful in larger applications.</p><h3>A Common Mistake</h3><p>Avoid doing this:</p><pre>class ProductProvider extends ChangeNotifier {<br>  final repository = ProductRepository(<br>    RealProductApi(),<br>  );<br>}</pre><p>Now ProductProvider is responsible for creating its dependency.</p><p>Instead:</p><pre>class ProductProvider extends ChangeNotifier {<br>  final ProductRepository repository;<br>  <br>ProductProvider({<br>    required this.repository,<br>  });<br>}</pre><p>And create the dependency somewhere outside:</p><pre>ProductProvider(<br>  repository: ProductRepository(<br>    RealProductApi(),<br>  ),<br>);</pre><p>This keeps responsibilities separated.</p><h3>The Bigger Picture</h3><p>Dependency Injection is really about <strong>separating object creation from object usage</strong>.</p><p>The ProductRepository should focus on:</p><blockquote><em>“How do I get products?”</em></blockquote><p>It shouldn’t also worry about:</p><blockquote><em>“Should I create a real API service?”</em></blockquote><p>The composition layer decides that.</p><p>So the architecture becomes:</p><pre>                Composition Root<br>                       │<br>              ┌────────┴────────┐<br>              ↓                 ↓<br>       RealProductApi      MockProductApi<br>              │                 │<br>              └────────┬────────┘<br>                       ↓<br>                ProductRepository<br>                       ↓<br>                 ProductProvider<br>                       ↓<br>                  ProductScreen</pre><p>This separation becomes increasingly valuable as an application grows.</p><h3>Final Thoughts</h3><p>Dependency Injection might initially look like unnecessary extra code.</p><p>Instead of:</p><pre>final api = RealProductApi();</pre><p>you might think:</p><blockquote><em>“Why should I pass this around?”</em></blockquote><p>But as your application grows, you’ll have multiple environments, APIs, databases, caches, analytics services, authentication services, and tests.</p><p>That’s when DI starts paying off.</p><p>The key idea to remember is simple:</p><blockquote><strong><em>Don’t make a class create the dependencies it needs. Give those dependencies to the class from outside.</em></strong></blockquote><p>Once you understand that principle, patterns like Repository, Clean Architecture, mocking, testing, and environment-based configuration become much easier to understand.</p><h4>If you’re working with Flutter, this is definitely a topic worth understanding beyond just knowing how to use a DI package.</h4><p>#Flutter #Dart #DependencyInjection #SoftwareArchitecture #CleanArchitecture #FlutterDevelopment #MobileDevelopment #Programming</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed72c1ad2b91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Tree Shaking in Flutter: How to Reduce App Size and Improve Performance]]></title>
            <link>https://medium.com/@pankajram1101/tree-shaking-in-flutter-how-to-reduce-app-size-and-improve-performance-bb518430f2af?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb518430f2af</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 05:42:57 GMT</pubDate>
            <atom:updated>2026-10-23T05:42:57.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rA2W_nCgxuhRUY7BG2vbkQ.png" /></figure><p>When building a Flutter application, we often focus on UI design, API integration, state management, and navigation. But there is another important concept that directly impacts the size of our production application: <strong>Tree Shaking</strong>.</p><p>Have you ever wondered why your Flutter app contains code that you never explicitly use? Or how Flutter can reduce the size of a release APK or app bundle without requiring you to manually remove unused code?</p><p>The answer lies in tree shaking.</p><p>In this article, we will explore what tree shaking is, how Flutter uses it, how to enable it, and what developers should know when optimizing production applications.</p><h3>🌱 What Is Tree Shaking?</h3><p>Tree shaking is a compiler optimization technique that removes unused code from the final application.</p><p>Imagine a tree with many branches. Some branches are necessary for the tree to grow, while others are unnecessary for a particular purpose. Tree shaking works similarly by identifying code that is not reachable from the application’s entry points and removing it from the compiled output when it is safe to do so.</p><p>Consider this example:</p><pre>void main() {<br>  printMessage();<br>}<br><br>void printMessage() {<br>  print(&#39;Hello Flutter!&#39;);<br>}<br><br>void unusedFunction() {<br>  print(&#39;This function is never called.&#39;);<br>}</pre><pre>In this example, main() calls printMessage(), but nothing calls unusedFunction().</pre><p>During compilation, Flutter’s Dart compiler can eliminate the unused function from the optimized release output.</p><p><strong>The result:</strong> Less unnecessary code in the final application.</p><p>However, tree shaking does not simply remove every function that is never directly called. The compiler must also consider indirect calls, reachable code, and other language features to determine what can safely be removed.</p><h3>⚙️ How Does Tree Shaking Work in Flutter?</h3><p>Flutter uses the Dart compilation toolchain to optimize applications for their target platforms.</p><p>The process can be understood in four steps:</p><p><strong>1. Entry-point identification</strong></p><p>The compiler starts from the application’s entry points, such as main(), and determines which code can be reached.</p><p><strong>2. Dependency analysis</strong></p><p>It analyzes function calls, class usage, references, and dependencies to identify the code required by the application.</p><p><strong>3. Dead-code elimination</strong></p><p>Code that cannot be reached and is safe to eliminate is removed from the optimized output.</p><p><strong>4. Optimized compilation</strong></p><p>For supported release targets, the compiler generates an optimized application containing the necessary code.</p><p>The exact compilation process differs by platform. For example, Flutter’s Android and iOS release builds use AOT (Ahead-of-Time) compilation, while Flutter web uses a different compilation pipeline.</p><h3>💻 Practical Example</h3><p>Let’s take a simple Flutter application:</p><pre>class Calculator {<br>  int add(int a, int b) {<br>    return a + b;<br>  }<br>  int subtract(int a, int b) {<br>    return a - b;<br>  }<br>  int multiply(int a, int b) {<br>    return a * b;<br>  }<br>}<br><br>void main() {<br>  final calculator = Calculator();<br>  print(calculator.add(10, 20));<br>}</pre><p>Suppose our application only uses the add() method.</p><p>Can tree shaking remove subtract() and multiply()?</p><p><strong>The answer depends on what the compiler can prove.</strong> Dart compilers perform reachability analysis and other optimizations, but you should not assume that every unused method inside a class will always be removed in every situation.</p><p>The compiler may eliminate unused methods when they are provably unnecessary. However, reflection-like mechanisms, dynamic dispatch, callbacks, or other indirect references can affect what is safe to remove.</p><p>The important takeaway is that tree shaking is a compiler optimization, not a manual code-cleanup tool.</p><h3>🚀 How to Enable Tree Shaking in Flutter</h3><p>For normal Flutter release builds, tree shaking and related compiler optimizations are generally handled automatically.</p><p>You do not need to enable a special flag just to get standard Dart tree shaking.</p><h3>1. Build an Android APK</h3><pre>flutter build apk --release</pre><h3>2. Build an Android App Bundle</h3><pre>flutter build appbundle --release</pre><h3>3. Build for iOS</h3><pre>flutter build ios --release</pre><h3>4. Build for Flutter Web</h3><pre>flutter build web --release</pre><p>These commands create release builds using the appropriate platform compilation pipeline.</p><p>Remember: debug builds prioritize development productivity, so their size and performance characteristics differ from release builds.</p><h3>🎨 An Important Example: Tree Shaking and Flutter Icons</h3><p>One of the most useful real-world examples is icon optimization.</p><p>Consider this code:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(<br>    const MaterialApp(<br>      home: Scaffold(<br>        body: Center(<br>          child: Icon(Icons.home),<br>        ),<br>      ),<br>    ),<br>  );<br>}</pre><pre>Flutter’s Material icon font can contain many icons, but your application may use only a small number of them.</pre><p>When building a release application, Flutter can tree-shake unused glyphs from supported icon fonts to reduce asset size.</p><p>For example, you may see output similar to:</p><pre>Font asset &quot;MaterialIcons-Regular.otf&quot;<br>was tree-shaken, reducing it from ...<br>to ...</pre><p>The actual size reduction depends on the icons used and the build configuration.</p><p>This is an excellent example of tree shaking working beyond ordinary Dart functions.</p><h3>What if you use icons dynamically?</h3><p>Suppose you load icon code points from an API or configuration file instead of referencing icons directly in your Dart code.</p><p>The compiler might not recognize those icons as required because their usage is not statically visible.</p><p>If your application genuinely needs a broader set of Material icons, you can disable icon-font tree shaking:</p><pre>flutter build apk --release --no-tree-shake-icons</pre><p>Use this option only when necessary. Disabling icon tree shaking can increase the size of your release application.</p><h3>📦 Tree Shaking vs. Other Flutter Optimizations</h3><p>These concepts are related, but they are not the same.</p><p>TechniquePurposeTree shakingRemoves unused code or supported unused font glyphsCode minificationShortens or transforms code where supportedAOT compilationCompiles Dart code ahead of execution for supported targetsImage optimizationReduces image asset sizesLazy loadingDefers loading or initialization until neededDependency optimizationAvoids unnecessary packages and dependencies</p><p>A smaller application does not automatically mean a faster application in every situation. Tree shaking primarily helps reduce the compiled output and associated download or storage costs.</p><h3>🛡️ Best Practices for Flutter Developers</h3><p>Here are some practical recommendations for production applications:</p><p><strong>1. Always measure release builds</strong></p><p>Do not estimate your final application size using a debug build.</p><pre>flutter build apk --release</pre><p>Compare the resulting artifact with earlier builds to identify meaningful changes.</p><p><strong>2. Avoid unnecessary dependencies</strong></p><p>Every dependency adds maintenance and potentially compilation, asset, or runtime costs. Remove packages you no longer need, but remember that unused package code may already be eliminated by the compiler.</p><p><strong>3. Be careful with dynamic code references</strong></p><p>If a feature depends on dynamically selected icons, callbacks, or other indirectly referenced resources, verify that the required resources survive release optimization.</p><p><strong>4. Test release builds properly</strong></p><p>A feature that works in debug mode should also be tested in a release build, particularly when relying on dynamically referenced resources or platform-specific behavior.</p><p><strong>5. Optimize assets separately</strong></p><p>Tree shaking will not automatically compress every image, video, or arbitrary asset in your project. Use appropriate image formats, resolutions, and asset-management strategies.</p><h3>🧠 Common Misconceptions</h3><p><strong>Myth 1: Tree shaking removes every unused dependency.</strong></p><p>Not necessarily. A dependency may contain code that is still reachable, and its assets or native components may have separate packaging behavior.</p><p><strong>Myth 2: Tree shaking improves runtime speed in every case.</strong></p><p>Its main benefit is reducing unnecessary compiled output. Performance improvements depend on the code and application.</p><p><strong>Myth 3: Developers must manually enable tree shaking for every Flutter release build.</strong></p><p>Standard Dart tree shaking is generally performed automatically. Icon tree shaking is also enabled by default for applicable release builds.</p><p><strong>Myth 4: Tree shaking removes unused images and all assets.</strong></p><p>No. Dart code elimination and icon-font optimization are different from general asset compression or removal.</p><h3>🎯 Final Thoughts</h3><p>Tree shaking is one of the important optimizations that makes Flutter production builds more efficient.</p><p>As Flutter developers, understanding how it works helps us make better decisions about dependencies, dynamic resources, icon usage, and release testing.</p><p>The key lesson is simple: <strong>Write clean, maintainable code, build in release mode, measure the output, and let the compiler remove code that is provably unnecessary.</strong></p><p>You do not always need to optimize manually. Sometimes, understanding what the compiler already does is the first step toward building a better application.</p><h3>👩‍💻 Keep Learning Flutter</h3><p>If you found this article useful, consider exploring these topics next:</p><ul><li>Flutter compilation: JIT vs. AOT</li><li>Flutter rendering pipeline: Widget, Element, and RenderObject</li><li>APK vs. AAB: How Android packages Flutter applications</li><li>Flutter performance profiling and DevTools</li><li>Reducing Flutter application size in production</li></ul><p><strong>What techniques do you use to reduce the size of your Flutter applications? Share your experience in the comments!</strong></p><p>#Flutter #Dart #MobileDevelopment #AppOptimization #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb518430f2af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Debugging BLoC with Print Statements — Use BlocObserver Instead ]]></title>
            <link>https://medium.com/@pankajram1101/stop-debugging-bloc-with-print-statements-use-blocobserver-instead-378ba30e48cc?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/378ba30e48cc</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 07:06:52 GMT</pubDate>
            <atom:updated>2026-08-18T07:06:52.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t80PXnw_Ue4KdJwwFK-yAg.png" /></figure><p>When working with <strong>BLoC or Cubit</strong> in Flutter, debugging state management can become difficult as the application grows.</p><p>You may have multiple BLoCs handling authentication, API calls, cart management, notifications, and UI state. Adding print() statements inside every BLoC works initially, but it quickly becomes messy.</p><p>This is where <strong>BlocObserver</strong> becomes extremely useful.</p><p>BlocObserver allows us to monitor BLoC and Cubit activity <strong>globally from a single place</strong>.</p><p>In this article, we’ll learn:</p><ul><li>What is BlocObserver?</li><li>Why should we use it?</li><li>How to create a custom observer</li><li>How to register it</li><li>Difference between onEvent, onChange, and onTransition</li><li>How to handle errors</li><li>A practical example</li><li>Best practices for production</li></ul><h3>What is BlocObserver?</h3><p>BlocObserver is a class provided by the flutter_bloc package that allows you to observe the lifecycle and behavior of all your BLoCs and Cubits.</p><p>Instead of writing:</p><pre>print(&quot;Counter event received&quot;);<br>print(&quot;State changed&quot;);<br>print(&quot;Error occurred&quot;);</pre><p>inside every BLoC, you can centralize this logging in one class.</p><p>The basic structure looks like this:</p><pre>class AppBlocObserver extends BlocObserver {<br>  @override<br>  void onCreate(BlocBase bloc) {<br>    super.onCreate(bloc);<br>  }<br><br>  @override<br>  void onEvent(Bloc bloc, Object? event) {<br>    super.onEvent(bloc, event);<br>  }<br><br>  @override<br>  void onChange(BlocBase bloc, Change change) {<br>    super.onChange(bloc, change);<br>  }<br><br>  @override<br>  void onTransition(<br>    Bloc bloc,<br>    Transition transition,<br>  ) {<br>    super.onTransition(bloc, transition);<br>  }<br><br>  @override<br>  void onError(<br>    BlocBase bloc,<br>    Object error,<br>    StackTrace stackTrace,<br>  ) {<br>    super.onError(bloc, error, stackTrace);<br>  }<br><br>  @override<br>  void onClose(BlocBase bloc) {<br>    super.onClose(bloc);<br>  }<br>}</pre><h3>Setting Up BlocObserver</h3><p>First, make sure you have flutter_bloc installed.</p><pre>dependencies:<br>  flutter_bloc: ^latest</pre><p>Then import it:</p><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;</pre><p>Now create your custom observer.</p><pre>class AppBlocObserver extends BlocObserver {<br>  <br>@override<br>  void onCreate(BlocBase bloc) {<br>    super.onCreate(bloc);<br>    print(&#39;onCreate: ${bloc.runtimeType}&#39;);<br>  }<br><br>  @override<br>  void onEvent(Bloc bloc, Object? event) {<br>    super.onEvent(bloc, event);<br>    print(<br>      &#39;onEvent: ${bloc.runtimeType} -&gt; $event&#39;,<br>    );<br>  }<br><br>  @override<br>  void onChange(BlocBase bloc, Change change) {<br>    super.onChange(bloc, change);<br>    print(<br>      &#39;onChange: ${bloc.runtimeType}\n&#39;<br>      &#39;Current State: ${change.currentState}\n&#39;<br>      &#39;Next State: ${change.nextState}&#39;,<br>    );<br>  }<br><br>  @override<br>  void onTransition(<br>    Bloc bloc,<br>    Transition transition,<br>  ) {<br>    super.onTransition(bloc, transition);<br>    print(<br>      &#39;onTransition: ${bloc.runtimeType}\n&#39;<br>      &#39;$transition&#39;,<br>    );<br>  }<br><br>  @override<br>  void onError(<br>    BlocBase bloc,<br>    Object error,<br>    StackTrace stackTrace,<br>  ) {<br>    super.onError(bloc, error, stackTrace);<br>    print(<br>      &#39;onError: ${bloc.runtimeType}\n&#39;<br>      &#39;Error: $error\n&#39;<br>      &#39;StackTrace: $stackTrace&#39;,<br>    );<br>  }<br><br>  @override<br>  void onClose(BlocBase bloc) {<br>    super.onClose(bloc);<br>    print(&#39;onClose: ${bloc.runtimeType}&#39;);<br>  }<br><br>}</pre><h3>Registering the Observer</h3><p>Creating the observer isn’t enough.</p><p>We need to register it with Bloc.observer.</p><p>The best place to do this is before runApp().</p><pre>void main() {<br>  Bloc.observer = AppBlocObserver();<br>  <br>  runApp(<br>    const MyApp(),<br>  );<br>}</pre><p>Now the observer will receive lifecycle callbacks from your BLoCs and Cubits.</p><h3>Understanding BlocObserver Methods</h3><p>Let’s understand the important methods one by one.</p><h3>1. onCreate()</h3><p>onCreate() is called when a BLoC or Cubit is created.</p><pre>@override<br>void onCreate(BlocBase bloc) {<br>  super.onCreate(bloc);<br>  print(&#39;onCreate: ${bloc.runtimeType}&#39;);<br>}</pre><p>For example, if you create:</p><pre>final counterCubit = CounterCubit();</pre><p>you may see:</p><pre>onCreate: CounterCubit</pre><p>This can be useful when debugging the lifecycle of your state management classes.</p><h3>2. onEvent()</h3><p>onEvent() is specific to <strong>BLoC</strong>.</p><p>It is called whenever an event is added to a BLoC.</p><p>For example:</p><pre>context.read&lt;CounterBloc&gt;().add(<br>  IncrementEvent(),<br>);</pre><p>The observer can capture that event:</p><pre>@override<br>void onEvent(Bloc bloc, Object? event) {<br>  super.onEvent(bloc, event);<br>  <br>  print(<br>    &#39;onEvent: ${bloc.runtimeType} -&gt; $event&#39;,<br>  );<br>}</pre><p>Output:</p><pre>onEvent: CounterBloc -&gt; IncrementEvent</pre><p>This is extremely useful when you want to know:</p><blockquote><em>Which event caused this operation?</em></blockquote><h3>3. onChange()</h3><p>onChange() is called whenever the state of a BlocBase changes.</p><p>BlocBase is the base class used by both BLoC and Cubit.</p><pre>@override<br>void onChange(BlocBase bloc, Change change) {<br>  super.onChange(bloc, change);<br>  print(<br>    &#39;Current: ${change.currentState}&#39;,<br>  );<br>  print(<br>    &#39;Next: ${change.nextState}&#39;,<br>  );<br>}</pre><pre>Suppose your Cubit starts with:</pre><pre>0</pre><p>and then changes to:</p><pre>1</pre><p>You might see:</p><pre>Current: 0<br>Next: 1</pre><p>This is particularly helpful for tracking state changes.</p><h3>4. onTransition()</h3><p>onTransition() is specific to <strong>BLoC</strong>.</p><p>A transition describes the movement from one state to another caused by an event.</p><p>Conceptually:</p><pre>Current State<br>      ↓<br>    Event<br>      ↓<br>  Next State</pre><p>For example:</p><pre>Current State: 0<br>Event: IncrementEvent<br>Next State: 1</pre><p>You can observe this using:</p><pre>@override<br>void onTransition(<br>  Bloc bloc,<br>  Transition transition,<br>) {<br>  super.onTransition(bloc, transition);<br>print(<br>    &#39;onTransition: ${bloc.runtimeType}\n&#39;<br>    &#39;$transition&#39;,<br>  );<br>}</pre><p>This is one of the most useful callbacks when debugging a BLoC-based application.</p><h3>5. onError()</h3><p>Errors are an important part of application debugging.</p><p>onError() allows you to observe errors generated by your BLoCs or Cubits.</p><pre>@override<br>void onError(<br>  BlocBase bloc,<br>  Object error,<br>  StackTrace stackTrace,<br>) {<br>  super.onError(<br>    bloc,<br>    error,<br>    stackTrace,<br>  );<br><br>print(<br>    &#39;Bloc: ${bloc.runtimeType}&#39;,<br>  );<br>  print(<br>    &#39;Error: $error&#39;,<br>  );<br>  print(<br>    &#39;StackTrace: $stackTrace&#39;,<br>  );<br>}</pre><p>For example:</p><pre>Bloc: LoginBloc<br>Error: Invalid credentials</pre><p>You can later replace print() with a proper logging or crash-reporting solution.</p><h3>6. onClose()</h3><p>onClose() is called when a BLoC or Cubit is closed.</p><pre>@override<br>void onClose(BlocBase bloc) {<br>  super.onClose(bloc);<br><br>  print(<br>    &#39;onClose: ${bloc.runtimeType}&#39;,<br>  );<br>}</pre><p>This is useful when investigating lifecycle and memory-related issues.</p><p>For example:</p><pre>onCreate: ProductBloc<br><br>...<br>onClose: ProductBloc</pre><p>This helps you understand when your BLoC is created and destroyed.</p><h3>BlocObserver with Cubit</h3><p>Let’s look at a simple Cubit.</p><pre>class CounterCubit extends Cubit&lt;int&gt; {<br>  CounterCubit() : super(0);<br>  <br>  void increment() {<br>    emit(state + 1);<br>  }<br>}</pre><p>When we call:</p><pre>context.read&lt;CounterCubit&gt;().increment();</pre><p>the state changes:</p><pre>0 → 1</pre><p>BlocObserver can capture this using onChange().</p><pre>onCreate: CounterCubit</pre><pre>onChange:<br>Current State: 0<br>Next State: 1</pre><p>Notice that there is no onEvent() here because Cubit does not use events.</p><h3>BlocObserver with BLoC</h3><p>Now let’s look at a BLoC.</p><pre>abstract class CounterEvent {}<br><br>class IncrementEvent extends CounterEvent {}<br>class CounterBloc extends Bloc&lt;CounterEvent, int&gt; {<br>  CounterBloc() : super(0) {<br>    on&lt;IncrementEvent&gt;((event, emit) {<br>      emit(state + 1);<br>    });<br>  }<br>}</pre><p>When we execute:</p><pre>context.read&lt;CounterBloc&gt;().add(<br>  IncrementEvent(),<br>);</pre><p>the observer can capture:</p><pre>onEvent:<br>CounterBloc -&gt; IncrementEvent</pre><pre>onTransition:<br>Current State: 0<br>Event: IncrementEvent<br>Next State: 1</pre><pre>onChange:<br>Current State: 0<br>Next State: 1</pre><p>This gives us a complete picture of what happened.</p><h3>onEvent vs onChange vs onTransition</h3><p>This is an important distinction.</p><h3>onEvent</h3><p>Tells you:</p><blockquote><em>Which event was added?</em></blockquote><pre>IncrementEvent</pre><h3>onTransition</h3><p>Tells you:</p><blockquote><em>Which event caused the state transition?</em></blockquote><pre>0 → IncrementEvent → 1</pre><h3>onChange</h3><p>Tells you:</p><blockquote><em>What state changed?</em></blockquote><pre>0 → 1</pre><p>A simple way to remember it:</p><pre>BLoC<br><br><br>Event<br>  ↓<br>onEvent()<br>  ↓<br>onTransition()<br>  ↓<br>onChange()</pre><h3>Complete Example</h3><p>Here is a simple complete implementation.</p><h3>Counter BLoC</h3><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>abstract class CounterEvent {}<br>class IncrementEvent extends CounterEvent {}<br>class DecrementEvent extends CounterEvent {}<br><br>class CounterBloc extends Bloc&lt;CounterEvent, int&gt; {<br>  CounterBloc() : super(0) {<br>    on&lt;IncrementEvent&gt;((event, emit) {<br>      emit(state + 1);<br>    });<br>    on&lt;DecrementEvent&gt;((event, emit) {<br>      emit(state - 1);<br>    });<br>  }<br>}</pre><h3>Observer</h3><pre>class AppBlocObserver extends BlocObserver {<br>  @override<br>  void onCreate(BlocBase bloc) {<br>    super.onCreate(bloc);<br>    print(<br>      &#39;Created: ${bloc.runtimeType}&#39;,<br>    );<br>  }<br>  @override<br>  void onEvent(Bloc bloc, Object? event) {<br>    super.onEvent(bloc, event);<br>    print(<br>      &#39;Event: ${bloc.runtimeType} -&gt; $event&#39;,<br>    );<br>  }<br>  @override<br>  void onTransition(<br>    Bloc bloc,<br>    Transition transition,<br>  ) {<br>    super.onTransition(bloc, transition);<br>    print(<br>      &#39;Transition: $transition&#39;,<br>    );<br>  }<br>  @override<br>  void onChange(<br>    BlocBase bloc,<br>    Change change,<br>  ) {<br>    super.onChange(bloc, change);<br>    print(<br>      &#39;Change: ${change.currentState} &#39;<br>      &#39;→ ${change.nextState}&#39;,<br>    );<br>  }<br>  @override<br>  void onError(<br>    BlocBase bloc,<br>    Object error,<br>    StackTrace stackTrace,<br>  ) {<br>    super.onError(<br>      bloc,<br>      error,<br>      stackTrace,<br>    );<br>    print(<br>      &#39;Error: $error&#39;,<br>    );<br>  }<br>  @override<br>  void onClose(BlocBase bloc) {<br>    super.onClose(bloc);<br>    print(<br>      &#39;Closed: ${bloc.runtimeType}&#39;,<br>    );<br>  }<br>}</pre><h3>main.dart</h3><pre>void main() {<br>  Bloc.observer = AppBlocObserver();</pre><pre>  runApp(<br>    const MyApp(),<br>  );<br>}</pre><p>Now your entire application can be monitored from one centralized observer.</p><h3>Why BlocObserver Is Useful</h3><p>There are several reasons to use BlocObserver.</p><h3>1. Centralized Logging</h3><p>Instead of writing logs inside every BLoC:</p><pre>print(&#39;Login started&#39;);<br>print(&#39;Login success&#39;);<br>print(&#39;Login failed&#39;);</pre><p>you can monitor BLoCs globally.</p><h3>2. Easier Debugging</h3><p>You can quickly identify:</p><ul><li>Which BLoC received an event</li><li>Which event caused a state change</li><li>What the previous state was</li><li>What the next state is</li><li>Where an error occurred</li></ul><h3>3. Lifecycle Monitoring</h3><p>onCreate() and onClose() can help you understand the lifecycle of your BLoCs and Cubits.</p><h3>4. Production Error Tracking</h3><p>onError() can be connected to tools such as crash reporting or centralized logging systems.</p><h3>Production Considerations</h3><p>Although BlocObserver is very useful, avoid blindly logging everything in production.</p><p>For example, this can expose sensitive information:</p><pre>print(change.nextState);</pre><p>If your state contains:</p><ul><li>Passwords</li><li>Authentication tokens</li><li>Personal information</li><li>Payment information</li><li>API credentials</li></ul><p>you should not log it.</p><p>A better approach is to conditionally enable verbose logging during development.</p><pre>void main() {<br>  Bloc.observer = AppBlocObserver();<br>  runApp(<br>    const MyApp(),<br>  );<br>}</pre><p>Your observer can also use a proper logging framework instead of print().</p><h3>Final Thoughts</h3><p>BlocObserver is a simple but powerful feature of the Flutter BLoC ecosystem.</p><p>It gives you a centralized way to observe:</p><pre>BLoC / Cubit<br>     │<br>     ├── onCreate()<br>     ├── onEvent()<br>     ├── onTransition()<br>     ├── onChange()<br>     ├── onError()<br>     └── onClose()</pre><p>Instead of debugging every BLoC individually, you can monitor your application’s state-management layer from a single location.</p><p>If you’re building a medium-to-large Flutter application using BLoC, having a well-designed BlocObserver can make debugging and monitoring significantly easier.</p><p>Yes. Since your GitHub project is now ready, add a <strong>Source Code</strong> section near the end of your Medium article, preferably <strong>before the final conclusion/LinkedIn section</strong>.</p><p>I recommend this:</p><h3>💻 Source Code</h3><p>Want to try BlocObserver yourself?</p><p>I’ve created a complete Flutter demo project that demonstrates:</p><ul><li>onCreate()</li><li>onEvent()</li><li>onTransition()</li><li>onChange()</li><li>onError()</li><li>onDone()</li><li>onClose()</li></ul><p>The project also includes a simple Counter BLoC so you can trigger these callbacks and see the logs directly in your Debug Console.</p><p>👉 <strong>View the complete source code on GitHub:</strong><br><a href="https://chatgpt.com/c/YOUR_GITHUB_REPOSITORY_URL"><strong>GitHub — Flutter BlocObserver Demo</strong></a></p><p>Feel free to ⭐ the repository if you find it useful!</p><h3>🤝 Let’s Connect</h3><p>If you enjoyed this article and want to learn more about <strong>Flutter, BLoC, Riverpod, and mobile app development</strong>, let’s connect on LinkedIn.</p><p>🔗 <a href="https://www.linkedin.com/in/pankaj-ram-ab85ba271/"><strong>Connect with me on LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=378ba30e48cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GoRouter NavigatorObserver in Flutter: Track Navigation Like a Pro]]></title>
            <link>https://medium.com/@pankajram1101/gorouter-navigatorobserver-in-flutter-track-navigation-like-a-pro-98fa29768b6d?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/98fa29768b6d</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 05:02:29 GMT</pubDate>
            <atom:updated>2026-08-02T05:02:29.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1U9coxTywW8F6mHeex-kIQ.png" /></figure><p>Navigation is one of the most important parts of any Flutter application. Whether you’re building a small app or a production-scale application, knowing <strong>which screen the user visited, when they navigated, and where they came from</strong> is extremely valuable.</p><p>If you’re using <strong>GoRouter</strong>, you might wonder:</p><blockquote><strong><em>How do I implement a RouterObserver similar to NavigatorObserver?</em></strong></blockquote><p>In this article, we’ll learn how to use NavigatorObserver with GoRouter, explore real-world production use cases, and build a reusable observer.</p><h3>Why Do We Need a RouterObserver?</h3><p>A NavigatorObserver allows you to listen to navigation events such as:</p><ul><li>Screen Push</li><li>Screen Pop</li><li>Route Replacement</li><li>Route Removal</li></ul><p>This is useful for:</p><ul><li>Analytics (Firebase Analytics, Mixpanel, CleverTap)</li><li>Debugging navigation</li><li>Logging user journeys</li><li>Measuring screen time</li><li>Triggering business logic on navigation</li></ul><h3>Creating a Custom NavigatorObserver</h3><p>Let’s create a reusable observer.</p><pre>class AppRouterObserver extends NavigatorObserver {<br>  @override<br>  void didPush(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) {<br>    debugPrint(<br>      &#39;PUSH -&gt; ${route.settings.name}&#39;<br>      &#39; | Previous -&gt; ${previousRoute?.settings.name}&#39;,<br>    );<br>  }<br><br>@override<br>  void didPop(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) {<br>    debugPrint(<br>      &#39;POP -&gt; ${route.settings.name}&#39;<br>      &#39; | Back To -&gt; ${previousRoute?.settings.name}&#39;,<br>    );<br>  }<br><br>  @override<br>  void didReplace({<br>    Route&lt;dynamic&gt;? newRoute,<br>    Route&lt;dynamic&gt;? oldRoute,<br>  }) {<br>    debugPrint(<br>      &#39;REPLACE -&gt; ${oldRoute?.settings.name}&#39;<br>      &#39; -&gt; ${newRoute?.settings.name}&#39;,<br>    );<br>  }<br><br>  @override<br>  void didRemove(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) {<br>    debugPrint(<br>      &#39;REMOVE -&gt; ${route.settings.name}&#39;,<br>    );<br>  }<br>}</pre><p>Now every navigation event can be monitored from one central place.</p><h3>Registering the Observer in GoRouter</h3><p>Unlike MaterialApp, you don&#39;t pass the observer to MaterialApp.router.</p><p>Instead, GoRouter provides an observers parameter.</p><pre>final router = GoRouter(<br>  observers: [<br>    AppRouterObserver(),<br>  ],<br>  routes: [<br>    GoRoute(<br>      name: &#39;home&#39;,<br>      path: &#39;/&#39;,<br>      builder: (_, __) =&gt; const HomeScreen(),<br>    ),<br>    GoRoute(<br>      name: &#39;profile&#39;,<br>      path: &#39;/profile&#39;,<br>      builder: (_, __) =&gt; const ProfileScreen(),<br>    ),<br>  ],<br>);</pre><p>Then configure your app normally.</p><pre>MaterialApp.router(<br>  routerConfig: router,<br>);</pre><p>That’s it! Your observer is now listening to every navigation event.</p><h3>Why Should Every Route Have a Name?</h3><p>Consider this route:</p><pre>GoRoute(<br>  path: &#39;/profile&#39;,<br>  builder: (_, __) =&gt; const ProfileScreen(),<br>)</pre><p>When navigating, the observer may print:</p><pre>PUSH -&gt; null</pre><p>Because no route name was provided.</p><p>Instead, define routes like this:</p><pre>GoRoute(<br>  name: &#39;profile&#39;,<br>  path: &#39;/profile&#39;,<br>  builder: (_, __) =&gt; const ProfileScreen(),<br>)</pre><p>Now you’ll get meaningful logs.</p><pre>PUSH -&gt; profile</pre><p>Named routes make analytics, debugging, and logging significantly easier.</p><h3>Production Use Cases</h3><h3>1. Analytics</h3><p>One of the most common uses of NavigatorObserver is tracking screen views.</p><pre>class AnalyticsObserver extends NavigatorObserver {<br>  @override<br>  void didPush(Route route, Route? previousRoute) {<br>    FirebaseAnalytics.instance.logScreenView(<br>      screenName: route.settings.name,<br>    );<br>  }<br>}</pre><p>Every screen visit is automatically reported to Firebase Analytics.</p><h3>2. Debug Navigation</h3><p>Instead of manually printing navigation calls throughout your codebase, you can centralize logging.</p><pre>PUSH -&gt; Home<br>PUSH -&gt; Product<br>PUSH -&gt; Product Details<br>POP -&gt; Product Details<br>Back To -&gt; Product</pre><p>This makes debugging navigation much easier.</p><h3>3. User Journey Tracking</h3><p>Suppose users frequently abandon the checkout process.</p><p>Using an observer, you can log the navigation flow:</p><pre>Home<br>↓<br>Product<br>↓<br>Cart<br>↓<br>Checkout<br>↓<br>Payment<br>↓<br>Success<br><br><br>This helps identify where users are dropping off.</pre><h3>4. Screen Time Analytics</h3><p>You can record when a screen is opened and calculate how long users stay on it.</p><p>Example:</p><pre>Profile Screen<br><br>Opened:<br>10:05:20<br>Closed:<br>10:07:31<br>Duration:<br>2m 11s</pre><p>This data is useful for engagement analysis.</p><h3>5. Automatic Cleanup</h3><p>When leaving a screen, you might want to:</p><ul><li>Stop a video player</li><li>Pause audio</li><li>Dispose resources</li><li>Cancel timers</li><li>Close WebSocket connections</li></ul><p>Observers provide a central place to perform these actions.</p><h3>Multiple Observers</h3><p>GoRouter supports multiple observers.</p><pre>final router = GoRouter(<br>  observers: [<br>    FirebaseAnalyticsObserver(<br>      analytics: FirebaseAnalytics.instance,<br>    ),<br>    AppRouterObserver(),<br>  ],<br>  routes: [<br>    // Routes<br>  ],<br>);</pre><p>This allows one observer to handle analytics while another handles logging or custom business logic.</p><h3>Best Practices</h3><p>✅ Give every route a unique name.</p><p>✅ Keep navigation logging centralized.</p><p>✅ Use observers for analytics instead of scattering tracking code across screens.</p><p>✅ Avoid putting business logic directly inside observers. Delegate it to dedicated services.</p><p>✅ Make your observer reusable so it can be shared across projects.</p><h3>Conclusion</h3><p>NavigatorObserver with GoRouter is a simple yet powerful feature that provides complete visibility into your application&#39;s navigation flow.</p><p>By implementing a custom observer, you can:</p><ul><li>Track every navigation event</li><li>Improve debugging</li><li>Integrate analytics</li><li>Measure user engagement</li><li>Keep your navigation logic centralized</li></ul><p>If you’re building production Flutter applications, adding a NavigatorObserver should be part of your application&#39;s architecture from day one.</p><h3>Let’s Connect</h3><p>I regularly share practical Flutter tutorials, architecture guides, and production-ready development tips. If you found this article helpful, feel free to connect with me and follow my work.</p><ul><li><strong>YouTube:</strong> <a href="https://www.youtube.com/@pankajram1101">https://www.youtube.com/@pankajram1101</a></li><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/pankaj-ram-ab85ba271/">https://www.linkedin.com/in/pankaj-ram-ab85ba271/</a></li><li><strong>Medium:</strong> <a href="https://medium.com/@pankajram1101">https://medium.com/@pankajram1101</a></li><li><strong>GitHub:</strong> <a href="https://github.com/pankaj1101">https://github.com/pankaj1101</a></li></ul><p>If you’d like to see more content on Flutter, Riverpod, GoRouter, Clean Architecture, and production best practices, subscribe to my YouTube channel and follow me on LinkedIn. Your support motivates me to create more in-depth technical content for the Flutter community.</p><p>Thanks for reading, and happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98fa29768b6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Event Loop in Flutter (Dart): A Complete Guide for Every Flutter Developer ]]></title>
            <link>https://medium.com/@pankajram1101/understanding-the-event-loop-in-flutter-dart-a-complete-guide-for-every-flutter-developer-a6adf01ad21b?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6adf01ad21b</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 07:15:39 GMT</pubDate>
            <atom:updated>2026-08-01T07:15:39.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhOgHrMLPmOhELiiRNmCrg.png" /></figure><p>When you start learning Flutter, you’ll quickly encounter keywords like <strong>Future</strong>, <strong>async</strong>, <strong>await</strong>, <strong>Streams</strong>, and <strong>Timers</strong>. They make asynchronous programming easy, but have you ever wondered <strong>how Dart executes all of these without freezing the UI?</strong></p><p>The answer is the <strong>Event Loop</strong>.</p><p>Understanding the Event Loop is one of the most important milestones for every Flutter developer. Once you understand it, many “magic” behaviors in Dart become predictable, and debugging asynchronous code becomes much easier.</p><p>In this article, we’ll explore the Event Loop from the ground up with practical examples.</p><h3>What is the Event Loop?</h3><p>The <strong>Event Loop</strong> is the mechanism that allows Dart to execute asynchronous code while keeping your Flutter application responsive.</p><p>A Flutter application runs inside a <strong>Dart Isolate</strong>, and each isolate has <strong>a single thread of execution</strong>.</p><p>This means:</p><ul><li>Only one piece of Dart code executes at a time.</li><li>Long-running operations should never block the main thread.</li><li>Asynchronous tasks are scheduled and executed by the Event Loop.</li></ul><p>Instead of waiting for an API response or a timer to finish, Dart continues executing other work. When the asynchronous task completes, its callback is added to a queue and executed later.</p><h3>Why Do We Need an Event Loop?</h3><p>Imagine you’re ordering food at a restaurant.</p><p>There’s only one chef.</p><p>If the chef waits 20 minutes beside the oven while your pizza bakes, no other customer gets served.</p><p>Instead, the chef:</p><ol><li>Places the pizza in the oven.</li><li>Starts preparing another order.</li><li>Returns to the pizza once it’s ready.</li></ol><p>That’s exactly how the Event Loop works.</p><p>Instead of waiting for an API or timer to complete, Dart continues processing other tasks.</p><h3>How the Event Loop Works</h3><p>Internally, Dart manages two important queues.</p><pre>Main Isolate</pre><pre>                    │<br>                    ▼<br>             ┌────────────┐<br>             │ Event Loop │<br>             └────────────┘<br>               ▲        ▲<br>               │        │<br>      Microtask Queue   Event Queue</pre><p>The Event Loop continuously checks these queues and executes tasks in a specific order.</p><h3>The Three Execution Stages</h3><p>Every Dart program follows the same execution sequence:</p><pre>Synchronous Code<br>        ↓<br>Microtask Queue<br>        ↓<br>Event Queue</pre><p>This order never changes.</p><p>Let’s understand each stage.</p><h3>1. Synchronous Code</h3><p>Synchronous code executes immediately.</p><p>Example:</p><pre>void main() {<br>  print(&quot;Hello&quot;);<br>  print(&quot;Flutter&quot;);<br>}</pre><p>Output:</p><pre>Hello<br>Flutter</pre><p>Every synchronous statement must complete before Dart starts processing asynchronous tasks.</p><h3>2. Microtask Queue</h3><p>The <strong>Microtask Queue</strong> contains high-priority asynchronous tasks.</p><p>Examples include:</p><ul><li>scheduleMicrotask()</li><li>Future.microtask()</li></ul><p>Microtasks always execute <strong>before</strong> the Event Queue.</p><p>Example:</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  print(&quot;Start&quot;);<br><br>  scheduleMicrotask(() {<br>    print(&quot;Microtask&quot;);<br>  });<br><br> print(&quot;End&quot;);<br>}</pre><p>Output:</p><pre>Start<br>End<br>Microtask</pre><p>The synchronous code executes first, then the microtask.</p><h3>3. Event Queue</h3><p>The Event Queue contains normal asynchronous work.</p><p>Examples include:</p><ul><li>Future()</li><li>Future.delayed()</li><li>Timer</li><li>User interactions</li><li>API responses</li><li>File I/O</li></ul><p>Example:</p><pre>void main() {<br>  print(&quot;Start&quot;);<br>  <br>  Future(() {<br>    print(&quot;Future&quot;);<br>  });<br><br>  print(&quot;End&quot;);<br><br>}</pre><p>Output:</p><pre>Start<br>End<br>Future</pre><p>The Future callback waits until all synchronous code has completed.</p><h3>Microtask Queue vs Event Queue</h3><p>Now let’s combine both.</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  print(&quot;A&quot;);<br>  <br>  Future(() {<br>    print(&quot;B&quot;);<br>  });<br><br>  scheduleMicrotask(() {<br>    print(&quot;C&quot;);<br>  });<br><br>  print(&quot;D&quot;);<br><br>}</pre><p>Most beginners expect:</p><pre>A<br>B<br>C<br>D</pre><p>But the actual output is:</p><pre>A<br>D<br>C<br>B</pre><p>Why?</p><p>Let’s see what happens step by step.</p><h3>Step 1</h3><pre>print(&quot;A&quot;);</pre><p>Output:</p><pre>A</pre><h3>Step 2</h3><pre>Future(...)</pre><p>The callback is added to the <strong>Event Queue</strong>.</p><h3>Step 3</h3><pre>scheduleMicrotask(...)</pre><p>The callback is added to the <strong>Microtask Queue</strong>.</p><h3>Step 4</h3><pre>print(&quot;D&quot;);</pre><p>Output:</p><pre>A<br>D</pre><p>Now all synchronous code has completed.</p><p>The Event Loop starts processing asynchronous tasks.</p><p>Since the <strong>Microtask Queue has higher priority</strong>, it executes first.</p><p>Output:</p><pre>C</pre><p>Only after the Microtask Queue becomes empty does Dart process the Event Queue.</p><p>Output:</p><pre>B</pre><p>Final Output:</p><pre>A<br>D<br>C<br>B</pre><h3>Understanding async and await</h3><p>Many developers think await blocks the application.</p><p>It doesn’t.</p><p>Example:</p><pre>Future&lt;void&gt; login() async {<br>  print(&quot;Login Started&quot;);<br>  <br>  await Future.delayed(<br>    const Duration(seconds: 2),<br>  );<br>  print(&quot;Login Completed&quot;);<br><br>}</pre><p>Here’s what happens:</p><ol><li>The function starts.</li><li>The timer begins.</li><li>The function pauses.</li><li>The Event Loop continues processing other work.</li><li>After two seconds, the function resumes.</li></ol><p>The UI never freezes.</p><h3>Future vs Future.microtask()</h3><p>Many developers don’t know the difference.</p><h3>Future</h3><pre>Future(() {<br>  print(&quot;Future&quot;);<br>});</pre><p>Added to:</p><ul><li>Event Queue</li></ul><h3>Future.microtask</h3><pre>Future.microtask(() {<br>  print(&quot;Microtask&quot;);<br>});</pre><p>Added to:</p><ul><li>Microtask Queue</li></ul><p>Since the Microtask Queue has higher priority, Future.microtask() executes before Future().</p><h3>Multiple Microtasks</h3><p>Example:</p><pre>void main() {<br>  print(&quot;Start&quot;);<br>  <br>  scheduleMicrotask(() =&gt; print(&quot;Microtask 1&quot;));<br>  scheduleMicrotask(() =&gt; print(&quot;Microtask 2&quot;));<br>  Future(() =&gt; print(&quot;Future&quot;));<br>  print(&quot;End&quot;);<br><br>}</pre><p>Output:</p><pre>Start<br>End<br>Microtask 1<br>Microtask 2<br>Future</pre><p>Notice that Dart processes <strong>all pending microtasks</strong> before moving to the Event Queue.</p><h3>Common Interview Question</h3><p>Predict the output.</p><pre>void main() {<br>  print(&quot;1&quot;);<br> Future(() {<br>    print(&quot;2&quot;);<br>  });<br>  Future.microtask(() {<br>    print(&quot;3&quot;);<br>  });<br>  print(&quot;4&quot;);<br>}</pre><p>Take a moment to think before checking the answer.</p><p>Output:</p><pre>1<br>4<br>3<br>2</pre><h3>Why Does Flutter Use the Event Loop?</h3><p>The Event Loop keeps your application responsive while handling:</p><ul><li>API calls</li><li>Database operations</li><li>File reading</li><li>Timers</li><li>Animations</li><li>User interactions</li></ul><p>Without it, your UI would freeze every time it waited for an asynchronous operation to complete.</p><h3>Best Practices</h3><p>✅ Use async and await instead of deeply nested callbacks.</p><p>✅ Avoid blocking the main isolate with heavy computations.</p><p>✅ Use compute() or Isolate.spawn() for CPU-intensive work.</p><p>✅ Understand the difference between Future() and Future.microtask().</p><p>✅ Keep the main thread free for rendering smooth UI.</p><h3>Key Takeaways</h3><ul><li>Dart executes code on a <strong>single thread per isolate</strong>.</li><li>The Event Loop manages all asynchronous operations.</li><li>Every program follows this execution order:</li></ul><pre>Synchronous Code<br>        ↓<br>Microtask Queue<br>        ↓<br>Event Queue</pre><ul><li>The <strong>Microtask Queue always has higher priority</strong> than the Event Queue.</li><li>await pauses the current function, not the entire application.</li><li>Understanding the Event Loop makes debugging asynchronous code much easier and helps you write more efficient Flutter applications.</li></ul><h3>Conclusion</h3><p>The Event Loop is the backbone of asynchronous programming in Dart. Whether you’re making API calls, listening to streams, using timers, or working with async/await, the Event Loop is constantly deciding <strong>what runs next</strong>.</p><p>Once you understand how synchronous code, the Microtask Queue, and the Event Queue work together, asynchronous programming becomes much less mysterious.</p><p>If you’re preparing for Flutter interviews or building production applications, mastering the Event Loop is a skill that will benefit you throughout your career.</p><h3>Connect with Me</h3><p>💼 <strong>LinkedIn:</strong><br><a href="https://www.linkedin.com/in/pankaj-ram-ab85ba271/">https://www.linkedin.com/in/pankaj-ram-ab85ba271/</a></p><p>💻 <strong>GitHub:</strong><br><a href="https://github.com/pankaj1101">https://github.com/pankaj1101</a></p><p>✍️ <strong>Medium:</strong><br><a href="https://medium.com/@pankajram1101">https://medium.com/@pankajram1101</a></p><p>If you found this article helpful, feel free to connect with me and follow for more Flutter and Dart deep dives. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6adf01ad21b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Error Handling Technique in Flutter Production Apps]]></title>
            <link>https://medium.com/@pankajram1101/best-error-handling-technique-in-flutter-production-apps-c9fc1639ff9d?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9fc1639ff9d</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 06:14:33 GMT</pubDate>
            <atom:updated>2026-07-30T06:22:07.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHsfrkV3L-5BTp8To53Unw.png" /></figure><p>No matter how well an application is built, things will eventually go wrong.</p><p>An API might fail.<br>The internet connection might be lost.<br>A server could return a 500 error.<br>JSON parsing may fail.<br>A timeout could occur.</p><p>The difference between a beginner and a production-ready Flutter application isn’t whether errors happen — it’s <strong>how those errors are handled</strong>.</p><p>In this article, we’ll explore a clean, scalable error handling strategy that is widely used in production Flutter applications.</p><h3>Why Traditional Error Handling Isn’t Enough</h3><p>Many Flutter developers start with this approach:</p><pre>try {<br>  final users = await api.getUsers();<br>} catch (e) {<br>  print(e);<br>}</pre><p>While this works for small projects, it quickly becomes difficult to maintain because:</p><ul><li>Every screen contains repetitive try-catch blocks.</li><li>Error messages are inconsistent.</li><li>Business logic becomes tightly coupled with exception handling.</li><li>Testing becomes more difficult.</li></ul><p>As applications grow, a better approach is needed.</p><h3>Production Architecture</h3><p>A common production architecture looks like this:</p><pre>UI<br>   ↓<br>Controller / ViewModel<br>   ↓<br>Repository<br>   ↓<br>Remote Data Source</pre><p>Each layer has a single responsibility.</p><ul><li><strong>Remote Data Source</strong> communicates with APIs.</li><li><strong>Repository</strong> converts exceptions into meaningful results.</li><li><strong>Controller</strong> updates the UI.</li><li><strong>UI</strong> simply displays the current state.</li></ul><h3>Avoid Throwing Exceptions to the UI</h3><p>Instead of allowing exceptions to bubble up to the presentation layer, return a result object.</p><pre>sealed class Result&lt;T&gt; {}<br><br>class Success&lt;T&gt; extends Result&lt;T&gt; {<br>  final T data;<br>  Success(this.data);<br>}<br><br>class Failure&lt;T&gt; extends Result&lt;T&gt; {<br>  final AppException exception;<br>  Failure(this.exception);<br>}</pre><p>Now every repository method returns either:</p><ul><li>Success</li><li>Failure</li></ul><p>instead of throwing exceptions.</p><h3>Create Custom Exceptions</h3><p>Rather than exposing raw exceptions to the UI, create meaningful exception types.</p><pre>sealed class AppException implements Exception {<br>  final String message;<br>  const AppException(this.message);<br>}<br><br>class NetworkException extends AppException {<br>  const NetworkException()<br>      : super(&quot;No Internet Connection&quot;);<br>}<br><br>class ServerException extends AppException {<br>  const ServerException()<br>      : super(&quot;Something went wrong on the server.&quot;);<br>}<br><br>class TimeoutException extends AppException {<br>  const TimeoutException()<br>      : super(&quot;Request timed out.&quot;);<br>}<br><br>class UnknownException extends AppException {<br>  const UnknownException()<br>      : super(&quot;Unexpected error occurred.&quot;);<br>}</pre><p>This keeps the UI independent from networking libraries such as Dio or http.</p><h3>Repository Example</h3><pre>Future&lt;Result&lt;List&lt;User&gt;&gt;&gt; getUsers() async {<br>  try {<br>    final users = await remoteDataSource.getUsers();<br>    return Success(users);<br>  } on SocketException {<br>    return Failure(NetworkException());<br>  } on TimeoutException {<br>    return Failure(TimeoutException());<br>  } catch (_) {<br>    return Failure(UnknownException());<br>  }<br>}</pre><p>Notice that no exceptions are thrown to the UI.</p><h3>Handle Results in the Controller</h3><pre>final result = await repository.getUsers();<br>switch (result) {<br>  case Success(:final data):<br>    state.value = UiSuccess(data);<br>   case Failure(:final exception):<br>    state.value = UiError(exception.message);<br>}</pre><p>The controller only cares about <strong>Success</strong> or <strong>Failure</strong>.</p><h3>Generic UI State</h3><p>A generic UI state keeps the presentation layer simple.</p><pre>sealed class UiState&lt;T&gt; {}<br><br>class Initial&lt;T&gt; extends UiState&lt;T&gt; {}<br><br>class Loading&lt;T&gt; extends UiState&lt;T&gt; {}<br><br>class Success&lt;T&gt; extends UiState&lt;T&gt; {<br>  final T data;<br> Success(this.data);<br>}<br><br>class Error&lt;T&gt; extends UiState&lt;T&gt; {<br>  final String message;<br>  Error(this.message);<br>}</pre><p>Every feature can reuse the same state.</p><pre>final usersState = Rx&lt;UiState&lt;List&lt;User&gt;&gt;&gt;(Initial());<br>final profileState = Rx&lt;UiState&lt;User&gt;&gt;(Initial());<br>final ordersState = Rx&lt;UiState&lt;List&lt;Order&gt;&gt;&gt;(Initial());</pre><p>This approach scales beautifully in large applications.</p><h3>Never Show Raw Exceptions</h3><p>Avoid displaying messages like:</p><pre>SocketException: Failed host lookup</pre><p>Instead, map them to user-friendly messages.</p><pre>❌ No Internet Connection<br>❌ Server is currently unavailable.<br>❌ Request timed out.<br>❌ Please try again later.</pre><p>Users should never see technical error messages.</p><h3>Log Errors Separately</h3><p>User-friendly messages are important, but developers still need detailed logs.</p><p>In production, integrate services such as:</p><ul><li>Firebase Crashlytics</li><li>Sentry</li></ul><p>Example:</p><pre>try {<br>  ...<br>} catch (e, stackTrace) {<br>  FirebaseCrashlytics.instance.recordError(<br>    e,<br>    stackTrace,<br>  );<br>}</pre><p>This allows developers to investigate crashes without exposing technical details to users.</p><h3>Retry Failed Requests</h3><p>Instead of asking users to restart the app, provide a retry option.</p><pre>ElevatedButton(<br>  onPressed: controller.fetchUsers,<br>  child: const Text(&quot;Retry&quot;),<br>)</pre><p>A simple retry button greatly improves user experience.</p><h3>Handle Offline Scenarios</h3><p>Production applications should gracefully handle the absence of an internet connection.</p><p>A common strategy is:</p><ul><li>Show cached data.</li><li>Display an offline banner.</li><li>Automatically refresh when connectivity returns.</li></ul><p>This creates a much smoother user experience.</p><h3>Common Mistakes</h3><p>❌ Throwing exceptions directly to the UI</p><p>❌ Showing raw API error messages</p><p>❌ Writing try-catch blocks in every screen</p><p>❌ Mixing networking code with UI logic</p><p>❌ Ignoring logging and crash reporting</p><h3>Production Error Handling Flow</h3><pre>API<br>   ↓<br>Remote Data Source<br>   ↓<br>Repository<br>   ↓<br>Result&lt;Success / Failure&gt;<br>   ↓<br>Controller<br>   ↓<br>UiState<br>   ↓<br>UI</pre><p>Every layer has a clear responsibility, making the codebase easier to maintain, test, and scale.</p><h3>Final Thoughts</h3><p>Error handling is much more than catching exceptions. It’s about designing an application that fails gracefully, communicates clearly with users, and remains easy to maintain as the project grows.</p><p>By combining:</p><ul><li>Repository Pattern</li><li>Custom Exceptions</li><li>Result</li><li>Generic UiState</li><li>Sealed Classes</li><li>Crash Reporting</li><li>Retry Mechanisms</li></ul><p>you can build Flutter applications that are robust, scalable, and production-ready.</p><p>Investing in a solid error handling strategy today will save countless debugging hours tomorrow.</p><h3>Connect With Me</h3><p>If you enjoyed this article and want to learn more about Flutter, Dart, Clean Architecture, Riverpod, GetX, and production-ready mobile development, feel free to connect with me.</p><p>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/pankaj-ram-ab85ba271/">https://www.linkedin.com/in/pankaj-ram-ab85ba271/</a></p><p>💻 <strong>GitHub:</strong> <a href="https://github.com/pankaj1101">https://github.com/pankaj1101</a></p><p>I regularly share practical Flutter tips, architecture guides, interview preparation, and real-world development techniques.</p><p>Happy Coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9fc1639ff9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dart 3 Records in Flutter: Write Cleaner and More Expressive Code]]></title>
            <link>https://medium.com/@pankajram1101/dart-3-records-in-flutter-write-cleaner-and-more-expressive-code-4de191dc7a5f?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/4de191dc7a5f</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 05:00:08 GMT</pubDate>
            <atom:updated>2026-07-30T05:00:08.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krtt2YIPxcKXj4agrWh3UA.png" /></figure><p>If you’ve been developing Flutter applications for a while, you’ve probably encountered situations where a function needs to return multiple values. Traditionally, developers created a dedicated model class for even the simplest use cases.</p><p>With <strong>Dart 3</strong>, <strong>Records</strong> provide a clean, type-safe way to group multiple values together without creating an additional class. They help reduce boilerplate while making your code more expressive.</p><p>In this article, we’ll explore what Records are, how to use them, and when they’re the right choice.</p><h3>What Are Records?</h3><p>A <strong>Record</strong> is a lightweight data structure that lets you group multiple values into a single object.</p><p>Unlike classes, Records don’t require constructors, fields, or methods. They’re designed for temporary data and function return values.</p><h3>Creating a Positional Record</h3><p>A positional record stores values in order.</p><pre>(String, int) user = (&quot;Pankaj&quot;, 25);</pre><pre>print(user.$1); // Pankaj<br>print(user.$2); // 25</pre><p>Values are accessed using $1, $2, $3, and so on.</p><p>Although positional records are concise, they become less readable as the number of values grows.</p><h3>Creating a Named Record</h3><p>Named records improve readability by assigning names to each field.</p><pre>({String name, int age}) user = (<br>  name: &quot;Pankaj&quot;,<br>  age: 25,<br>);</pre><pre>print(user.name);<br>print(user.age);</pre><p>This makes the code self-explanatory and easier to maintain.</p><h3>Returning Multiple Values</h3><p>One of the most common uses of Records is returning multiple values from a function.</p><pre>({bool success, String message}) login() {<br>  return (<br>    success: true,<br>    message: &quot;Login Successful&quot;,<br>  );<br>}</pre><p>Using the returned record:</p><pre>final result = login();</pre><pre>print(result.success);<br>print(result.message);</pre><p>This approach avoids creating a dedicated model when the data is only needed temporarily.</p><h3>Destructuring Records</h3><p>Dart also supports destructuring, allowing you to extract values directly into local variables.</p><pre>final (:name, :age) = (<br>  name: &quot;Pankaj&quot;,<br>  age: 25,<br>);</pre><pre>print(name);<br>print(age);</pre><p>This keeps your code concise and improves readability.</p><h3>Passing Records as Parameters</h3><p>Records can also be passed directly to functions.</p><pre>void printUser(({String name, int age}) user) {<br>  print(user.name);<br>  print(user.age);<br>}</pre><pre>printUser((<br>  name: &quot;Pankaj&quot;,<br>  age: 25,<br>));</pre><h3>Type Safety</h3><p>Records are strongly typed.</p><pre>(String, int) user = (&quot;Flutter&quot;, 3);</pre><p>The compiler knows:</p><ul><li>First value is a String</li><li>Second value is an int</li></ul><p>This provides compile-time safety while keeping the syntax lightweight.</p><h3>When Should You Use Records?</h3><p>Records work best when:</p><ul><li>Returning multiple values from a function.</li><li>Creating temporary data structures.</li><li>Passing small groups of related values.</li><li>Writing helper or utility methods.</li><li>Reducing unnecessary boilerplate.</li></ul><h3>When Should You Avoid Records?</h3><p>Records are <strong>not</strong> a replacement for classes.</p><p>Avoid using them for:</p><ul><li>API response models.</li><li>Database entities.</li><li>Business/domain objects.</li><li>Objects that contain behaviour or business logic.</li><li>Long-lived application state.</li></ul><p>If the data represents an important concept in your application, a dedicated class remains the better choice.</p><h3>Why Records Matter</h3><p>Records help you write cleaner code by eliminating small classes whose only purpose is to hold two or three values.</p><p>They improve readability, reduce boilerplate, and encourage more expressive APIs without sacrificing type safety.</p><h3>Conclusion</h3><p>Records are one of the most useful additions introduced in Dart 3. While they’re simple, they can significantly improve the quality of your Flutter code by making common tasks easier and more concise.</p><p>The key is knowing <strong>when</strong> to use them. Use Records for lightweight, temporary data, and continue using classes for rich domain models.</p><p>Small language features often have the biggest impact on day-to-day development — and Records are a great example of that.</p><p><strong>If you’re already using Dart 3, try replacing a few helper classes with Records in your next Flutter project. You might be surprised by how much cleaner your code becomes.</strong></p><h3>Connect With Me</h3><p>If you found this article helpful and would like to explore more Flutter and Dart content, feel free to connect with me.</p><p>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/pankaj-ram-ab85ba271/">https://www.linkedin.com/in/pankaj-ram-ab85ba271/</a></p><p>💻 <strong>GitHub:</strong> <a href="https://github.com/pankaj1101">https://github.com/pankaj1101</a></p><p>I regularly share content on Flutter, Dart, Riverpod, performance optimization, architecture, and mobile app development. If you enjoy learning about Flutter, let’s connect and grow together!</p><p>Happy Coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4de191dc7a5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slack API Error Notification using Node.js]]></title>
            <link>https://medium.com/@pankajram1101/slack-api-error-notification-using-node-js-a13fc2340c14?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/a13fc2340c14</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 15:17:09 GMT</pubDate>
            <atom:updated>2026-04-08T03:18:27.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nk07xagE14oRFJLPgpXQaA.png" /></figure><h3>1. Overview</h3><p>This document explains how to implement <strong>automatic Slack notifications when an API fails</strong> in a <strong>Node.js Express application</strong>.</p><p>When an API throws an error, the system will send a message to a <strong>Slack channel</strong> containing:</p><ul><li>API Route</li><li>HTTP Method</li><li>Error Message</li><li>Timestamp</li><li>Stack trace (optional)</li></ul><p>This helps developers <strong>monitor production errors quickly</strong>.</p><h3>2. Architecture Flow</h3><pre>Client Request<br>      ↓<br>Node.js API<br>      ↓<br>Error Occurs<br>      ↓<br>Global Error Middleware<br>      ↓<br>Slack Webhook Triggered<br>      ↓<br>Message sent to Slack Channel</pre><h3>3. Prerequisites</h3><p>Before implementing the solution ensure:</p><ul><li>Node.js installed (v16+ recommended)</li><li>npm installed</li><li>Slack workspace access</li><li>Permission to create Slack Apps</li></ul><h3>4. Project Setup</h3><h4>Step 1: Initialize Node Project</h4><pre>npm init -y</pre><p>This creates:</p><pre>package.json</pre><h4>Step 2: Install Required Dependencies</h4><p>Install necessary packages:</p><pre>npm install express axios dotenv</pre><p>Dependencies used: express, axios, dotenv</p><h3>5. Slack Webhook Setup</h3><h4>Step 1: Create Slack App</h4><p>Go to:</p><p><a href="https://api.slack.com/apps">Slack API: Applications | Slack</a></p><p>Click:</p><pre>Create New App</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ai4vYr35lm20fPeO9ZHCTg.png" /></figure><p>Choose:</p><pre>From Scratch</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1iqnvVsxsvOc7CmDO9qXUw.png" /></figure><p>Select your <strong>workspace</strong>.</p><h4>Step 2: Enable Incoming Webhook</h4><p>Navigate to:</p><pre>Incoming Webhooks → Activate</pre><p>Enable the toggle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kq6xnG158RKHCWX36IiTDw.png" /></figure><h4>Step 3: Create Webhook URL</h4><p>Click:</p><pre>Add New Webhook to Workspace</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6wFpCShlm8CAWjytTW-7g.png" /></figure><p>Select the Slack channel where errors should be sent.</p><p>Example channel:</p><pre>#api-errors</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPA8uG-PTJNDNP5tMVsLjA.png" /></figure><p>Slack will generate a <strong>Webhook URL</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5wwfkO-g-w4hUmZ6p6PMw.png" /></figure><pre>https://hooks.slack.com/services/TXXXXX/BXXXXX/XXXXXXXX<br></pre><h3>6. Environment Configuration</h3><p>Create a .env file:</p><pre>.env</pre><p>Add the webhook URL:</p><pre>SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXXXX<br>PORT=3000</pre><h3>7. Project Folder Structure</h3><p>Recommended structure:</p><pre>project-root<br>│<br>├── node_modules<br>├── services<br>│   └── slackNotifier.js<br>│<br>├── middleware<br>│   └── errorMiddleware.js<br>│<br>├── routes<br>│   └── sampleRoute.js<br>│<br>├── app.js<br>├── package.json<br>└── .env</pre><h3>8. Slack Notification Service</h3><p>Create file:</p><pre>services/slackNotifier.js</pre><pre>const axios = require(&quot;axios&quot;);<br><br>const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;<br>async function sendSlackError(message) {<br>  try {<br>    await axios.post(SLACK_WEBHOOK_URL, {<br>      text: message,<br>    });<br>  } catch (error) {<br>    console.error(&quot;Slack notification failed:&quot;, error.message);<br>  }<br>}<br>module.exports = sendSlackError;</pre><p>Purpose:</p><ul><li>Sends POST request to Slack webhook</li><li>Delivers error message to Slack channel</li></ul><h3>9. Global Error Middleware</h3><p>Create file:</p><pre>middleware/errorMiddleware.js</pre><pre>const sendSlackError = require(&quot;../services/slackNotifier&quot;);<br><br>function errorMiddleware(err, req, res, next) {<br>  <br>const errorMessage = `<br>🚨 *API FAILED*<br>Route: ${req.originalUrl}<br>Method: ${req.method}<br>Error: ${err.message}<br>Time: ${new Date().toISOString()}<br>\`\`\`<br>${err.stack}<br>\`\`\`<br>`;<br><br>  sendSlackError(errorMessage);<br><br>  res.status(500).json({<br>    message: &quot;Internal Server Error&quot;<br>  });<br><br>}<br><br>module.exports = errorMiddleware;</pre><p>This middleware:</p><ul><li>Captures all API errors</li><li>Sends notification to Slack</li><li>Returns HTTP 500 response</li></ul><h3>10. Sample Route with Error</h3><p>Create:</p><pre>routes/sampleRoute.js</pre><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br><br>router.get(&quot;/test-error&quot;, async (req, res, next) =&gt; {<br>  try {<br>    throw new Error(&quot;Database connection failed&quot;);<br>  } catch (error) {<br>    next(error);<br>  }<br>});<br><br>module.exports = router;</pre><h3>11. Main Application File</h3><p>Create:</p><pre>app.js</pre><pre>require(&quot;dotenv&quot;).config();<br><br>const express = require(&quot;express&quot;);<br>const sampleRoute = require(&quot;./routes/sampleRoute&quot;);<br>const errorMiddleware = require(&quot;./middleware/errorMiddleware&quot;);<br><br>const app = express();<br>app.use(express.json());<br><br>app.use(&quot;/api&quot;, sampleRoute);<br>app.use(errorMiddleware);<br><br>const PORT = process.env.PORT || 3000;<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on http://localhost:${PORT}`);<br>});</pre><h3>12. Running the Application</h3><p>Start server:</p><pre>node app.js</pre><p>Server will run on:</p><pre>http://localhost:3000</pre><h3>13. Test the Error Notification</h3><p>Call the API:</p><pre>http://localhost:3000/api/test-error</pre><p>The API will throw an error.</p><p>Slack will receive message like:</p><pre>🚨 API FAILED<br><br>Route: /api/test-error<br>Method: GET<br>Error: Database connection failed<br>Time: 2026-03-17T11:12:45Z</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysWZvo0ny6mzHqzEeAxsZA.png" /></figure><h3>14. Best Practices</h3><h3>Use Environment Variables</h3><p>Never hardcode webhook URL.</p><p>Always store it in .env.</p><h3>Avoid Blocking API Response</h3><p>Do not wait for Slack response:</p><pre>sendSlackError(message);</pre><p>instead of</p><pre>await sendSlackError(message);</pre><h3>Include Additional Metadata</h3><p>Useful fields:</p><ul><li>User ID</li><li>Request body</li><li>Environment (Dev/Prod)</li><li>Service name</li></ul><p>Example:</p><pre>Environment: Production<br>Service: Auth API</pre><h3>15. Optional Enhancements</h3><h3>Add API Name</h3><pre>API: Create User</pre><h3>Send Request Body</h3><pre>Payload: ${JSON.stringify(req.body)}</pre><h3>Send User Info</h3><pre>User: ${req.user?.id}</pre><h3>16. Production Monitoring Tools</h3><p>Large systems combine Slack alerts with monitoring tools:</p><p>ToolPurposeSentryError trackingDatadogObservabilityNew RelicPerformance monitoringPrometheusMetrics</p><p>Slack is commonly used for <strong>real-time alerts</strong>.</p><h3>17. Security Considerations</h3><ul><li>Keep webhook URL secret</li><li>Use environment variables</li><li>Do not expose .env in GitHub</li></ul><p>Add to .gitignore:</p><pre>.env<br>node_modules</pre><h3>18. Summary</h3><p>This implementation allows:</p><ul><li>Automatic Slack alerts</li><li>Centralized error handling</li><li>Production monitoring</li></ul><p>Key components:</p><ol><li>Slack Webhook</li><li>Error Notification Service</li><li>Global Error Middleware</li><li>Express API integration</li></ol><p>✅ Result:</p><p>Whenever an API fails, the team will instantly receive a <strong>Slack alert</strong> with detailed error information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a13fc2340c14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Custom Dropdowns from Scratch in Flutter]]></title>
            <link>https://medium.com/@pankajram1101/creating-custom-dropdowns-from-scratch-in-flutter-44b6a5652915?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b6a5652915</guid>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 05:57:07 GMT</pubDate>
            <atom:updated>2025-10-05T05:57:07.402Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Flutter gives you beautiful built-in widgets, but sometimes your design needs something </em>extra<em>.</em></blockquote><blockquote><em>In this post, we’ll build </em><strong><em>two fully custom dropdowns from scratch</em></strong><em> — one for forms (generic, reusable) and one for advanced UI (overlay-based).</em></blockquote><p>By the end, you’ll know how to design dropdowns that match your brand, your theme, and your creativity — not just the default Material look.</p><h3>🧩 1. The Generic Reusable Dropdown</h3><p>Let’s start with a simple but reusable dropdown — perfect for forms, GST selections, or category filters.</p><p>Instead of rewriting DropdownButtonFormField everywhere, we’ll create a <strong>generic widget</strong> that supports validation, theming, and custom text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AkgN7WukFC-nyb-eDjB6g.png" /><figcaption>Generic Reusable Dropdown</figcaption></figure><h3>💻 Code</h3><pre>import &#39;package:financial_calculator/core/theme/dimension.dart&#39;;<br>import &#39;package:financial_calculator/core/utils/app_colors.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br><br>class DropdownFormField&lt;T&gt; extends StatelessWidget {<br>  final List&lt;DropdownMenuItem&lt;T&gt;&gt; items;<br>  final T? value;<br>  final String? hint;<br>  final String? labelText;<br>  final Function(T?) onChanged;<br>  final FormFieldValidator&lt;T&gt;? validator;<br><br> const DropdownFormField({<br>    Key? key,<br>    required this.items,<br>    this.value,<br>    this.hint,<br>    this.labelText,<br>    required this.onChanged,<br>    this.validator,<br>  }) : super(key: key);<br>  <br>@override<br>  Widget build(BuildContext context) {<br>    return DropdownButtonFormField&lt;T&gt;(<br>      hint: Text(<br>        hint ?? &#39;&#39;,<br>        style: const TextStyle(color: AppColors.titleColor),<br>      ),<br>      value: value,<br>      items: items,<br>      onChanged: onChanged,<br>      validator: validator,<br>      decoration: InputDecoration(<br>        labelText: labelText,<br>        floatingLabelBehavior: FloatingLabelBehavior.always,<br>        border: OutlineInputBorder(<br>          borderRadius: BorderRadius.circular(Dimension.defaultBorderRadius),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>✅ Usage Example</h3><pre>DropdownFormField&lt;String&gt;(<br>  items: controller.depositTypeList<br>      .map((value) =&gt; DropdownMenuItem(<br>            value: value,<br>            child: Text(&#39;$value%&#39;),<br>          ))<br>      .toList(),<br>  value: controller.selectedGstRatesValue ?? controller.depositTypeList.first,<br>  labelText: &#39;GST %&#39;,<br>  onChanged: (value) {<br>    controller.setselectedGstRatesValue(value!);<br>  },<br>  validator: (value) {<br>    if (value == null) {<br>      return &#39;Please select GST %&#39;;<br>    }<br>    return null;<br>  },<br>);</pre><h3>💡 Why Use This Approach?</h3><ul><li>✅ Reusable across screens</li><li>✅ Works with any data type (&lt;T&gt;)</li><li>✅ Cleaner form code</li><li>✅ Consistent design system</li></ul><h3>⚡ 2. Overlay Dropdown — The Power of Flexibility</h3><p>Now let’s step up.<br> What if you want more control? A dropdown that floats above other widgets, with custom animations or icons?</p><p>That’s where <strong>Flutter’s Overlay widget</strong> shines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qI3Qz8J2T5SmDrZLbhcaQ.png" /><figcaption>Overlay Dropdown</figcaption></figure><h3>💻 Code</h3><pre>class DropdownItem {<br>  final int id;<br>  final String name;<br>  DropdownItem({required this.id, required this.name});<br>}</pre><pre>class OverlayDropdown extends StatefulWidget {<br>  final List&lt;DropdownItem&gt; items;<br>  final String hintText;<br>  final ValueChanged&lt;DropdownItem&gt; onChanged;</pre><pre>  const OverlayDropdown({<br>    super.key,<br>    required this.items,<br>    required this.hintText,<br>    required this.onChanged,<br>  });</pre><pre>  @override<br>  State&lt;OverlayDropdown&gt; createState() =&gt; _OverlayDropdownState();<br>}</pre><pre>class _OverlayDropdownState extends State&lt;OverlayDropdown&gt; {<br>  final LayerLink _layerLink = LayerLink();<br>  OverlayEntry? _overlayEntry;<br>  String? _selectedValue;<br>  bool _isDropdownOpen = false;</pre><pre>  void _toggleDropdown() {<br>    _isDropdownOpen ? _removeDropdown() : _showDropdown();<br>  }</pre><pre>  void _showDropdown() {<br>    final overlay = Overlay.of(context);<br>    final renderBox = context.findRenderObject() as RenderBox;<br>    final size = renderBox.size;</pre><pre>    _overlayEntry = OverlayEntry(<br>      builder: (context) =&gt; Positioned(<br>        width: size.width,<br>        child: CompositedTransformFollower(<br>          link: _layerLink,<br>          offset: Offset(0, size.height + 4),<br>          child: Material(<br>            elevation: 1,<br>            borderRadius: BorderRadius.circular(8),<br>            child: ListView(<br>              padding: EdgeInsets.zero,<br>              shrinkWrap: true,<br>              children: widget.items.map((item) {<br>                return ListTile(<br>                  title: Text(item.name),<br>                  onTap: () {<br>                    setState(() =&gt; _selectedValue = item.name);<br>                    widget.onChanged(item);<br>                    _removeDropdown();<br>                  },<br>                );<br>              }).toList(),<br>            ),<br>          ),<br>        ),<br>      ),<br>    );</pre><pre>    overlay.insert(_overlayEntry!);<br>    setState(() =&gt; _isDropdownOpen = true);<br>  }</pre><pre>  void _removeDropdown() {<br>    _overlayEntry?.remove();<br>    _overlayEntry = null;<br>    setState(() =&gt; _isDropdownOpen = false);<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return CompositedTransformTarget(<br>      link: _layerLink,<br>      child: GestureDetector(<br>        onTap: _toggleDropdown,<br>        child: Container(<br>          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),<br>          decoration: BoxDecoration(<br>            border: Border.all(color: Colors.grey.shade400),<br>            borderRadius: BorderRadius.circular(8),<br>          ),<br>          child: Row(<br>            mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>            children: [<br>              Text(<br>                _selectedValue ?? widget.hintText,<br>                style: TextStyle(<br>                  color: _selectedValue == null ? Colors.grey : Colors.black,<br>                ),<br>              ),<br>              Icon(<br>                _isDropdownOpen ? Icons.arrow_drop_up : Icons.arrow_drop_down,<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }</pre><pre>  @override<br>  void dispose() {<br>    _removeDropdown();<br>    super.dispose();<br>  }<br>}</pre><h3>✅ Usage Example</h3><pre>final items = [<br>  DropdownItem(id: 1, name: &#39;Apple&#39;),<br>  DropdownItem(id: 2, name: &#39;Banana&#39;),<br>  DropdownItem(id: 3, name: &#39;Mango&#39;),<br>  DropdownItem(id: 4, name: &#39;Orange&#39;),<br>];</pre><pre>OverlayDropdown(<br>  items: items,<br>  hintText: &#39;Select Fruit&#39;,<br>  onChanged: (value) {<br>    debugPrint(&#39;Selected Id: ${value.id}&#39;);<br>    debugPrint(&#39;Selected Name: ${value.name}&#39;);<br>  },<br>);</pre><h3>💪 Why Overlay Dropdown?</h3><p>✅ You control position &amp; size<br> ✅ Ideal for filters, menus, and search lists</p><h3>🚀 Wrap-Up</h3><p>Both dropdowns are awesome in their own right:</p><p>Use Case Best Option Simple Forms Generic Dropdown Advanced UI / Filters Overlay Dropdown</p><p>Mix and match depending on your app’s design system.</p><h3>✨ Bonus Tip</h3><p>You can animate your Overlay Dropdown using FadeTransition, SlideTransition, or even with AnimatedContainer for a smooth, modern feel.</p><h3>❤️ If you liked this post</h3><ul><li>👏 Clap if you learned something new</li><li>💬 Comment if you’d like me to share a <strong>searchable dropdown</strong> next</li><li>🔔 Follow for more <strong>Flutter UI design patterns</strong></li></ul><p>#Flutter #FlutterUI #UIDesign #MobileDevelopment #FlutterWidgets #OverlayWidget #Dart</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b6a5652915" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing API URLs in Flutter Using FFI on Android]]></title>
            <link>https://medium.com/@pankajram1101/securing-api-urls-in-flutter-using-ffi-on-android-af16a0c40947?source=rss-dd2152474d41------2</link>
            <guid isPermaLink="false">https://medium.com/p/af16a0c40947</guid>
            <dc:creator><![CDATA[Pankaj Ram]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 14:52:50 GMT</pubDate>
            <atom:updated>2025-09-28T14:52:50.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*7lrOfX72Xu6HPtR3-54ybg.png" /></figure><p>In mobile app development, storing sensitive information like API URLs directly in your app is risky. Flutter developers often seek ways to secure such data. One approach is using <strong>Flutter FFI (Foreign Function Interface)</strong> to store and retrieve URLs from a <strong>native C/C++ library</strong>. This makes it harder for attackers to reverse-engineer your app.</p><p>In this post, I’ll guide you through implementing a <strong>secure API URL using FFI on Android</strong>.</p><h3>Why FFI?</h3><p>Flutter runs on Dart, which is relatively easy to decompile. By storing critical data in a <strong>native library (</strong><strong>.so)</strong>, we make it much harder to extract API URLs from the APK.</p><ul><li>Android: .so libraries compiled with NDK</li><li>iOS: Would require Xcode (not covered here)</li></ul><h3>Step 1: Write the C Library</h3><p>Create a simple C file secure_url.c:</p><pre>#include &lt;stdio.h&gt;</pre><pre>const char* get_api_base_url() {<br>    return &quot;https://your-secure-api.com/&quot;;<br>}</pre><blockquote><em>For C++, use </em><em>extern &quot;C&quot;:</em></blockquote><pre>extern &quot;C&quot; const char* get_api_base_url() {<br>    return &quot;https://your-secure-api.com/&quot;;<br>}</pre><h3>Step 2: Compile .so for Android ABIs</h3><p>Android devices have different architectures:</p><p>ABI Target triple for clang arm64-v8a aarch64-linux-android21 armeabi-v7a armv7a-linux-androideabi21 x86 i686-linux-android21 x86_64 x86_64-linux-android21</p><p>You can compile using <strong>NDK clang</strong>:</p><pre># Example: ARM64<br>&amp; &quot;C:\Users\Lenovo\AppData\Local\Android\Sdk\ndk\26.3.11579264\toolchains\llvm\prebuilt\windows-x86_64\bin\clang.exe&quot; --target=aarch64-linux-android21 -shared -fPIC -o android\app\src\main\jniLibs\arm64-v8a\libsecure_url.so secure_url.c</pre><blockquote><em>Running this for all ABIs ensures your app works on any device or emulator.</em></blockquote><h3>Step 2a: Automate compilation for all ABIs</h3><p>You can use this PowerShell script:</p><pre>$ndk = &quot;C:\Users\Lenovo\AppData\Local\Android\Sdk\ndk\26.3.11579264&quot;<br>$abis = @{<br>    &quot;armeabi-v7a&quot; = &quot;armv7a-linux-androideabi21&quot;<br>    &quot;arm64-v8a&quot;   = &quot;aarch64-linux-android21&quot;<br>    &quot;x86&quot;         = &quot;i686-linux-android21&quot;<br>    &quot;x86_64&quot;      = &quot;x86_64-linux-android21&quot;<br>}<br>$source = &quot;secure_url.c&quot;</pre><pre>foreach ($abi in $abis.Keys) {<br>    $target = $abis[$abi]<br>    $outDir = &quot;android\app\src\main\jniLibs\$abi&quot;<br>    if (!(Test-Path $outDir)) { New-Item -ItemType Directory -Force -Path $outDir }<br>    &amp; &quot;$ndk\toolchains\llvm\prebuilt\windows-x86_64\bin\clang.exe&quot; --target=$target -shared -fPIC -o &quot;$outDir\libsecure_url.so&quot; $source<br>}</pre><ul><li>Compiles .so for <strong>all Android ABIs</strong> automatically.</li><li>Saves time and prevents dlopen errors due to ABI mismatch.</li></ul><h3>Step 3: Configure Gradle for JNI Libraries</h3><p>In android/app/build.gradle.kts (Kotlin DSL):</p><pre>android {<br>    sourceSets {<br>        getByName(&quot;main&quot;) {<br>            jniLibs.srcDirs(&quot;src/main/jniLibs&quot;)<br>        }<br>    }<br>}</pre><ul><li>This ensures Flutter includes the .so libraries in the APK.</li></ul><h3>Step 4: Use FFI in Flutter</h3><pre>import &#39;dart:ffi&#39;;<br>import &#39;package:ffi/ffi.dart&#39;;</pre><pre>typedef _get_api_base_url_func = Pointer&lt;Utf8&gt; Function();<br>typedef _GetApiBaseUrl = Pointer&lt;Utf8&gt; Function();</pre><pre>class SecureUrl {<br>  late DynamicLibrary _dylib;</pre><pre>  SecureUrl() {<br>    _dylib = DynamicLibrary.open(&quot;libsecure_url.so&quot;);<br>  }</pre><pre>  String getApiBaseUrl() {<br>    final _GetApiBaseUrl getUrl = _dylib<br>        .lookup&lt;NativeFunction&lt;_get_api_base_url_func&gt;&gt;(&#39;get_api_base_url&#39;)<br>        .asFunction();<br>    return getUrl().toDartString();<br>  }<br>}</pre><ul><li>DynamicLibrary.open() loads the .so file.</li><li>Calling getApiBaseUrl() retrieves the <strong>secure URL</strong>.</li></ul><h3>Step 5: Run on Android</h3><ul><li>Place .so files in correct ABI folders:</li></ul><pre>android/app/src/main/jniLibs/armeabi-v7a/libsecure_url.so<br>android/app/src/main/jniLibs/arm64-v8a/libsecure_url.so<br>android/app/src/main/jniLibs/x86/libsecure_url.so<br>android/app/src/main/jniLibs/x86_64/libsecure_url.so</pre><ul><li>Run Flutter:</li></ul><pre>flutter clean<br>flutter pub get<br>flutter run</pre><ul><li>Flutter automatically picks the correct .so depending on device ABI.</li></ul><h3>✅ Result</h3><ul><li>API URL is now stored in a <strong>native library</strong>, making it harder to extract.</li><li>Works on <strong>all Android devices and emulators</strong>.</li><li>No ABI mismatch errors like dlopen failed. Still you face an issue you can dm connect me on linkedln.</li></ul><h3>Tip</h3><p>If you also want <strong>iOS support</strong>, you’ll need <strong>Xcode</strong> to compile a universal static library (.a). Without a Mac, you can use <strong>Dart-only obfuscation</strong> to secure URLs across platforms.</p><h3>Conclusion</h3><p>Using <strong>Flutter FFI</strong> with a <strong>C/C++ native library</strong> is a practical way to secure sensitive data on Android.</p><ul><li>Multi-ABI compilation is key for compatibility.</li><li>Gradle must include jniLibs folders correctly.</li><li>Dart FFI API allows seamless integration.</li></ul><p>Connect with me:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/pankaj-ram-ab85ba271/">https://www.linkedin.com/in/pankaj-ram-ab85ba271/</a></li><li><strong>GitHub: </strong><a href="https://github.com/pankaj1101">https://github.com/pankaj1101</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af16a0c40947" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>