<?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 Syed Mahamudul Hasan on Medium]]></title>
        <description><![CDATA[Stories by Syed Mahamudul Hasan on Medium]]></description>
        <link>https://medium.com/@syedhasan.cse?source=rss-77a892bc9b3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bgXpkkQtfpcQMyeN</url>
            <title>Stories by Syed Mahamudul Hasan on Medium</title>
            <link>https://medium.com/@syedhasan.cse?source=rss-77a892bc9b3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:06:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@syedhasan.cse/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[Why context.mounted Is Crashing Your Flutter App in Production]]></title>
            <link>https://medium.com/@syedhasan.cse/why-context-mounted-is-crashing-your-flutter-app-in-production-e36bbf8f6a3f?source=rss-77a892bc9b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e36bbf8f6a3f</guid>
            <category><![CDATA[crashlytics]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Syed Mahamudul Hasan]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 08:01:55 GMT</pubDate>
            <atom:updated>2026-07-29T08:01:55.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmqgWqChzLkcq8NLWBtDhg.png" /></figure><h3>The subtle distinction between mounted and context.mounted that leads to hidden null-check exceptions in StatefulWidget.</h3><p><strong>TL;DR:</strong> Inside a StatefulWidget’s State class, checking if (!context.mounted) return; after an await boundary can throw a fatal <strong>Null check operator used on a null value</strong> exception in production. Always use <strong>mounted</strong> when inside a State class, and reserve <strong>context.mounted</strong> for StatelessWidget or standalone functions.</p><h3>1. Introduction: The Mysterious Crashlytics Stack Trace</h3><p>Have you ever opened your Firebase Crashlytics dashboard to find a mysterious fatal error that looks like this?</p><pre>Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError:<br>Null check operator used on a null value.<br> at State.context(framework.dart:959)<br> at _MyWidgetState.myAsyncMethod(my_widget.dart:231)</pre><p>You open my_widget.dart at line 231, expecting to see an unhandled nullable object, but instead, you see this:</p><pre>if (!context.mounted) return;</pre><p><strong>Wasn’t context.mounted introduced in Flutter 3.7 specifically to write safe asynchronous code across BuildContext boundaries? Why is a safety check throwing a fatal crash inside framework.dart?</strong></p><h3>2. How We Got Here: The Linter Trap</h3><p>When Flutter introduced the <strong>use_build_context_synchronously</strong> lint rule, static analysis started warning developers whenever a BuildContext was used across an async gap:</p><pre>// Linter Warning: Do not use BuildContexts across async gaps<br>Future&lt;void&gt; _handleTap() async {<br> await fetchUserData();<br> Navigator.of(context).pop(); <br>}</pre><blockquote>To fix this warning, developers naturally follow the IDE quick-fix, which inserts <strong>if (!context.mounted) return;</strong>.</blockquote><p>While this works perfectly fine in many places, applying it blindly inside a StatefulWidget creates a hidden edge case.</p><h3>3. Under the Hood: mounted vs. context.mounted</h3><p>In a StatefulWidget, there are two ways to check if a component is still active in the widget tree:</p><ul><li><strong>mounted (a property directly on the State class)</strong></li><li><strong>context.mounted (a property on BuildContext)</strong></li></ul><h3>3.1 How State.mounted Works</h3><p>Inside <strong>framework.dart</strong>, the mounted property on the State class is implemented as a simple null-check against its internal _element:</p><pre>// Inside framework.dart (State class)<br>bool get mounted =&gt; _element != null;</pre><p>If the user navigates away or disposes of the widget while an asynchronous operation is running, _element becomes null. Evaluating mounted simply returns false. It is completely safe and free of side effects.</p><h3>3.2 How context.mounted Works inside State</h3><p>When you write context.mounted inside a State class, Dart must first resolve the context getter on State before it can access .mounted.</p><p>Here is how State.context is defined in framework.dart:</p><pre>// Inside framework.dart (State class)<br>BuildContext get context {<br> assert(_element != null, &#39;State object is unmounted&#39;);<br> return _element!; // The fatal null-assertion operator<br>}</pre><p>Notice the _element! return statement:</p><ul><li><strong>In Debug Mode:</strong> An assertion triggers with a helpful error message.</li><li><strong>In Release/Production Mode:</strong> Assertions are stripped out. If _element is null because the widget was unmounted during the await call, _element! executes directly and throws a <strong>Null check operator used on a null value</strong> exception.</li></ul><h3>4. Comparison Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*k0ms_T1pzBmbfRdfliHFBg.png" /><figcaption>Comparison of `mounted` vs. `context.mounted` in Flutter</figcaption></figure><h3>5. The Solution &amp; Best Practices</h3><h3>Scenario 1: Inside a StatefulWidget (Use mounted)</h3><p>Always use the mounted getter provided directly by the State class.</p><pre>// BAD: Can crash if unmounted during fetchUserData()<br>Future&lt;void&gt; loadData() async {<br> await fetchUserData();<br> if (!context.mounted) return; <br> setState(() { … });<br>}<br>// GOOD: Safely returns false if unmounted<br>Future&lt;void&gt; loadData() async {<br> await fetchUserData();<br> if (!mounted) return; <br> setState(() { … });<br>}</pre><h3>Scenario 2: Inside a StatelessWidget or Helper Function (Use context.mounted)</h3><p>Because StatelessWidget and standalone functions do not have a State object, context.mounted is the correct and intended approach.</p><pre>// GOOD: Standard usage in a helper function passing BuildContext<br>Future&lt;void&gt; performAction(BuildContext context) async {<br> await processPayment();<br> <br> if (!context.mounted) return;<br> <br> Navigator.of(context).pop();<br>}</pre><h3>6. Summary Rule of Thumb</h3><ul><li><strong>Inside State&lt;T&gt;: Always use mounted.</strong></li><li><strong>Outside State&lt;T&gt; (Stateless / Functions): Use context.mounted.</strong></li></ul><h3>7. Audit Your Codebase Today</h3><p>To check if your project is vulnerable to this issue, search your codebase using regex for occurrences of context.mounted inside your state classes:</p><pre>if\s*\(!context\.mounted\)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e36bbf8f6a3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Railway Oriented Programming (ROP) in Dart]]></title>
            <link>https://medium.com/@syedhasan.cse/railway-oriented-programming-rop-in-dart-568b3b14e6f3?source=rss-77a892bc9b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/568b3b14e6f3</guid>
            <category><![CDATA[rop]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Syed Mahamudul Hasan]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 06:24:24 GMT</pubDate>
            <atom:updated>2025-04-21T06:24:24.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LANYHVRiyI2AwQptpsoluw.png" /><figcaption>Railway Oriented Programming</figcaption></figure><p>Railway Oriented Programming is a functional pattern for error handling and composition. It visualizes logic flow as two tracks: success and failure. Instead of throwing exceptions, you pass results (success/failure) down a pipeline.</p><h4>Why Use ROP?</h4><ul><li>Prevents unhandled exceptions.</li><li>Makes the flow of success and failure explicit.</li><li>Great for chaining operations with built-in error short-circuiting.</li><li>Ideal for clean, predictable, and maintainable business logic.</li><li>Enhances debugging with clear branching logic.</li></ul><h4>When to Use ROP?</h4><p>🔹 In complex pipelines where multiple operations can fail.<br> 🔹 When dealing with user input validation or chained service calls.<br> 🔹 When applying functional or clean architecture patterns.<br> 🔹 To replace try-catch-heavy code with a predictable flow.</p><h4>Basic Implementation</h4><pre>abstract class Result&lt;T&gt; {}<br> <br> class Success&lt;T&gt; extends Result&lt;T&gt; {<br> final T value;<br> Success(this.value);<br> }<br> <br> class Failure&lt;T&gt; extends Result&lt;T&gt; {<br> final String message;<br> Failure(this.message);<br> }</pre><h4>Chaining with Railway Switches</h4><pre>Result&lt;String&gt; validate(String input) {<br> return input.isEmpty ? Failure(&quot;Input is empty&quot;) : Success(input);<br> }<br> <br> Result&lt;String&gt; toUpperCase(String input) {<br> return Success(input.toUpperCase());<br> }<br> <br> Result&lt;int&gt; countCharacters(String input) {<br> return Success(input.length);<br> }</pre><h4>Function Pipeline</h4><pre>Result&lt;int&gt; process(String input) {<br> final step1 = validate(input);<br> if (step1 is Failure) return step1;<br> <br> final step2 = toUpperCase((step1 as Success).value);<br> if (step2 is Failure) return step2;<br> <br> final step3 = countCharacters((step2 as Success).value);<br> return step3;<br> }</pre><h4>Handling the Result</h4><pre>final result = process(&quot;hello&quot;);<br> <br> if (result is Success&lt;int&gt;) {<br> print(&quot;Character count: ${result.value}&quot;);<br> } else if (result is Failure) {<br> print(&quot;Error: ${result.message}&quot;);<br> }</pre><h4>Async Example</h4><pre>Future&lt;Result&lt;String&gt;&gt; fetchUserName() async {<br> try {<br> await Future.delayed(Duration(seconds: 1));<br> return Success(&#39;Syed Mahamudul Hasan&#39;);<br> } catch (e) {<br> return Failure(&#39;Failed to fetch user&#39;);<br> }<br> }</pre><h4>Elegant Handling with when</h4><pre>extension ResultX&lt;T&gt; on Result&lt;T&gt; {<br>  R when&lt;R&gt;({<br>    required R Function(T value) success,<br>    required R Function(String message) failure,<br>  }) {<br>    if (this is Success&lt;T&gt;) return success((this as Success&lt;T&gt;).value);<br>    return failure((this as Failure&lt;T&gt;).message);<br>  }<br>}<br><br>Usage:<br><br>result.when(<br>  success: (val) =&gt; print(val),<br>  failure: (msg) =&gt; print(msg),<br>);</pre><h4>Summary</h4><p><strong>Railway Oriented Programming (ROP)</strong> in Dart is a functional approach to error handling where each function returns a Result—either Success or Failure. This pattern models logic like a railway track: if one step fails, the rest are skipped, making the flow clean and predictable. It’s ideal for chaining multiple operations that might fail, such as input validation or service calls, without using try-catch blocks. ROP improves maintainability and readability, especially in clean architecture, and can be enhanced with extensions like when() for elegant result handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=568b3b14e6f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Multiple  API Calls with Future.any in Flutter]]></title>
            <link>https://medium.com/@syedhasan.cse/efficient-multiple-api-calls-with-future-any-in-flutter-ef354b6a75cf?source=rss-77a892bc9b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef354b6a75cf</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Syed Mahamudul Hasan]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 06:12:59 GMT</pubDate>
            <atom:updated>2025-04-18T06:12:59.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient Multiple API Calls with Future.any in Flutter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kv76Aipbu0m2nioBGeRamg.png" /></figure><h3>Overview</h3><p>In certain scenarios, an app screen requires data from multiple APIs to display different sections. While calling these APIs one after another ensures sequential loading, it significantly reduces app performance and increases wait time.</p><p>To enhance responsiveness and speed, Dart offers Future.any to initiate multiple API calls concurrently and proceed with whichever completes first.</p><h3>Why Sequential API Calls Reduce Performance</h3><p>Sequential API calls mean the second request will only be made once the first one is completed. This leads to increased latency, especially if each API has variable response time.</p><p>Example:</p><pre>await fetchUserInfo();<br>await fetchUserPosts();<br>await fetchUserNotifications();</pre><p>In this approach, total time = time for API1 + API2 + API3 (cumulative).</p><h3>Using Future.any for Performance Boost</h3><p>Instead of waiting for each API to complete, you can use Future.any to trigger all API calls at once and proceed with the fastest one.</p><pre>Future.any([<br>  fetchUserInfo(),<br>  fetchUserPosts(),<br>  fetchUserNotifications()<br>]).then((value) {<br>  // Use whichever result comes first<br>});</pre><p>This allows the UI to show data from the fastest API while others complete in the background, improving perceived performance and user experience.</p><h3>When to Use Future.any</h3><ul><li>When you have fallback APIs and need only one successful response.</li><li>When displaying partial data quickly is better than showing a loading indicator.</li><li>When enhancing responsiveness is more important than receiving every dataset immediately.</li></ul><h3>Alternatives</h3><ul><li>Future.wait: Waits for all futures to complete.</li><li>Future.race: Similar to Future.any but completes with first settled (success or failure) future.</li></ul><h3>Conclusion</h3><p>Using Future.any can significantly reduce wait time and enhance app responsiveness by letting your app proceed with the quickest response, rather than waiting for all API calls to complete. Ideal for non-blocking UI patterns in Flutter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef354b6a75cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Pagination with NotificationListener]]></title>
            <link>https://medium.com/@syedhasan.cse/flutter-pagination-with-notificationlistener-a2830f9ef186?source=rss-77a892bc9b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2830f9ef186</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[scroll]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Syed Mahamudul Hasan]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 11:46:02 GMT</pubDate>
            <atom:updated>2025-04-13T11:47:53.106Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The Simplest Way to Add Pagination in Flutter with NotificationListener</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjQd7e-FHIkOScKtrTaOpw.png" /></figure><p>Smooth Pagination in Flutter with NotificationListener</p><p>When working with lists in Flutter — especially in apps like social feeds, quiz apps, or chat applications — pagination becomes essential. You don’t want to load hundreds of items at once and slow down the user experience.<br> <br> In this post, we’ll look at how to implement scroll-based pagination using Flutter’s built-in NotificationListener widget.</p><h3>Why NotificationListener?</h3><p>NotificationListener&lt;ScrollNotification&gt; allows you to listen to scroll-related events such as:<br> — ScrollStartNotification<br> — ScrollUpdateNotification<br> — ScrollEndNotification<br> <br> By listening for ScrollEndNotification, we can detect when the user finishes scrolling — and then load more data if needed.</p><h3>💡 Real-World Example: Quiz App Pagination</h3><p>Imagine a quiz app where each question is loaded from a backend. You don’t want to load all questions at once. Instead, as the user scrolls down, you fetch more questions.</p><p>Example Code:</p><pre>NotificationListener&lt;ScrollNotification&gt;(<br>  if (notification is ScrollEndNotification &amp;&amp;<br>                    notification.metrics.extentAfter == 0) {<br>                  if (controller.loadNextPage.isFalse &amp;&amp;<br>                      controller.currentPage &lt;= controller.lastPage) {<br>                    // Set loading flag<br>                    controller.loadNextPage(true);<br>                    // Increment the page number<br>                    controller.currentPage++;<br>                    // Fetch the next page of data<br>                    controller.fetchQuestionsData();<br>                  }<br>                }<br>                // Return true to indicate the notification has been handled<br>                return true;<br>);</pre><h3>🔍 Code Breakdown:</h3><p>- ScrollEndNotification: Fires when user stops scrolling.<br> — fetchQuestionsData(): Function that gets the next set of questions from an API or local DB.</p><h3>✅ Advantages of This Approach</h3><p>- Built-In Support: No need for third-party libraries.<br> — Performance: Fetch only what’s needed.<br> — Simple: Clear separation of concerns.<br> — Customizable: Use your own pagination logic or state management (like GetX, BLoC, etc.).</p><h3>🧠 Pro Tips</h3><p>1. Add a loading spinner at the bottom while new data loads.<br> 2. Pair this with a ScrollController for more control over scroll position and animation.<br> 3. If working with APIs, always debounce or throttle fetch calls to avoid spamming requests.</p><h3>🏁 Conclusion</h3><p>Using NotificationListener for pagination is a clean and efficient way to load data as users scroll. Whether it’s a social feed, infinite list, or quiz questions, this method keeps your UI responsive and your code organized.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2830f9ef186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GetX ever Method Explained: The Easiest Way to Handle State Changes]]></title>
            <link>https://medium.com/@syedhasan.cse/getx-ever-method-explained-the-easiest-way-to-handle-state-changes-e6113e52583a?source=rss-77a892bc9b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6113e52583a</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[getx]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ever]]></category>
            <dc:creator><![CDATA[Syed Mahamudul Hasan]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 18:01:15 GMT</pubDate>
            <atom:updated>2025-02-12T18:01:15.164Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>GetX provides a simple and efficient way to manage state in Flutter. One of its most useful reactive methods is ever, which allows you to execute a function every time a specific variable changes. This is especially handy for handling side effects like API calls, logging, or UI updates.</p><h3>Understanding ever</h3><p>The ever method listens to changes in a reactive variable and executes a callback function whenever the variable updates.</p><h3>Syntax:</h3><pre>ever(Rx variable, void Function(T) callback);</pre><ul><li><strong>variable</strong>: The reactive variable to watch.</li><li><strong>callback</strong>: A function that runs every time the variable changes.</li></ul><h3>Example Usage</h3><h3>Example 1: API Call on Value Change</h3><p>Imagine you have a search bar, and you want to fetch results every time the user updates the search query.</p><pre>class SearchController extends GetxController {<br>  var query = &#39;&#39;.obs;</pre><pre>  @override<br>  void onInit() {<br>    ever(query, (value) {<br>      fetchSearchResults(value);<br>    });<br>    super.onInit();<br>  }</pre><pre>  void fetchSearchResults(String query) {<br>    print(&#39;Fetching results for: $query&#39;);<br>  }<br>}</pre><p><strong>How it works:</strong></p><ul><li>Whenever query changes, fetchSearchResults is called with the updated value.</li><li>No need to manually set up listeners — GetX handles it for you!</li></ul><h3>Example 2: Showing a Snackbar on State Change</h3><p>If you want to show a message when a user logs in successfully, you can use ever like this:</p><pre>class AuthController extends GetxController {<br>  var isLoggedIn = false.obs;</pre><pre>  @override<br>  void onInit() {<br>    ever(isLoggedIn, (value) {<br>      if (value) {<br>        Get.snackbar(&#39;Success&#39;, &#39;You are now logged in!&#39;);<br>      }<br>    });<br>    super.onInit();<br>  }</pre><pre>  void login() {<br>    isLoggedIn.value = true; // This triggers the snackbar<br>  }<br>}</pre><h3>When to Use ever?</h3><p>✅ When you need to perform actions <strong>immediately</strong> after a variable changes.<br> ✅ For triggering API calls, logging, analytics, or UI updates.<br> ✅ When you want <strong>automatic reactions</strong> to state changes without manually handling listeners.</p><h3>Conclusion</h3><p>The ever method in GetX simplifies state-based reactions, reducing boilerplate and making your code cleaner. Whether fetching data, showing alerts, or logging events, ever ensures your app stays responsive to state changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6113e52583a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Real-Time Communication in Flutter with Pusher Channels: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@syedhasan.cse/implementing-real-time-communication-in-flutter-with-pusher-channels-a-step-by-step-guide-891db932e431?source=rss-77a892bc9b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/891db932e431</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[pusher]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[stream]]></category>
            <dc:creator><![CDATA[Syed Mahamudul Hasan]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 15:54:28 GMT</pubDate>
            <atom:updated>2025-02-04T15:54:28.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Real-time communication is a cornerstone of modern applications, enabling features like live chat, notifications, and collaborative tools. In this post, we’ll explore how to integrate <strong>Pusher Channels</strong> into a Flutter app using the pusher_channels_flutter package. We’ll walk through a production-ready implementation that handles authentication, event streaming, and connection management.</p><p>Why Pusher Channels?<br>Pusher Channels simplifies real-time communication by abstracting WebSocket complexities. It offers:</p><p>Scalable pub/sub messaging</p><p>Presence channels for user tracking</p><p>Built-in authentication and security</p><p>Cross-platform support</p><h3>Implementation Overview</h3><p>Here’s the architecture of our Flutter implementation:</p><ol><li><strong>Pusher Initialization</strong>: Configure keys, cluster, and authentication.</li><li><strong>Authentication</strong>: Secure channels using a backend token.</li><li><strong>Event Streaming</strong>: Broadcast events via a StreamController.</li><li><strong>Connection Management</strong>: Handle states, errors, and cleanup.</li></ol><h3>Step 1: Setting Up Pusher</h3><p>We start by initializing Pusher and connecting to a channel:</p><pre>Future&lt;void&gt; initPusher(String channelName) async {<br>  pusher = PusherChannelsFlutter.getInstance();<br>  await pusher.init(<br>    apiKey: pusherKey,<br>    cluster: cluster,<br>    onAuthorizer: onAuthorizer, // Handles auth<br>    // ... other callbacks<br>  );<br>  await pusher.subscribe(channelName: channelName);<br>  await pusher.connect();<br>}</pre><p><strong>Key Points</strong>:</p><ul><li>Use cluster for regional optimization.</li><li>onAuthorizer ensures only authenticated users access channels.</li></ul><h3>Step 2: Authentication</h3><p>To secure channels, implement onAuthorizer to fetch a token from your backend:</p><pre>dynamic onAuthorizer(String channelName, String socketId, dynamic options) async {<br>  final response = await dioClient().post(<br>    &quot;${baseUrl}/broadcasting/auth&quot;,<br>    data: &#39;socket_id=$socketId&amp;channel_name=$channelName&#39;,<br>    headers: {&#39;Authorization&#39;: &#39;Bearer $userToken&#39;},<br>  );<br>  return response.data; // Returns auth signature<br>}</pre><p><strong>Best Practices</strong>:</p><ul><li>Always use HTTPS for auth endpoints.</li><li>Validate user permissions server-side.</li></ul><h3>Step 3: Handling Events</h3><p>Use a StreamController to broadcast incoming events across your app:</p><pre>final StreamController&lt;PusherEvent&gt; _eventController = <br>  StreamController&lt;PusherEvent&gt;.broadcast();<br>void onEvent(PusherEvent event) {<br>  _eventController.sink.add(event); // Broadcast to listeners<br>}<br>// Example usage in a widget:<br>PusherServices.instance.eventStream.listen((event) {<br>  print(&#39;New message: ${event.data}&#39;);<br>});</pre><p><strong>Use Cases</strong>:</p><ul><li>Update UI in real-time</li><li>Trigger background tasks</li><li>Sync data across devices</li></ul><h3>Step 4: Managing Connections</h3><p>Handle connection states and errors gracefully:</p><pre>void onConnectionStateChange(dynamic currentState, dynamic previousState) {<br>  debugPrint(&quot;Connection: $currentState&quot;);<br>}<br>void onError(String message, int? code, dynamic e) {<br>  debugPrint(&quot;Error: $message&quot;);<br>  // Implement retry logic here<br>}</pre><p><strong>Pro Tips</strong>:</p><ul><li>Use connection states to show UI indicators (e.g., “Reconnecting…”).</li><li>Log errors for debugging.</li></ul><h3>Step 5: Cleanup</h3><p>Avoid memory leaks by closing streams and disconnecting Pusher:</p><pre>@override<br>void onClose() {<br>  _eventController.close();<br>  pusher.unsubscribe(channelName: channelName);<br>  pusher.disconnect();<br>  super.onClose();<br>}</pre><h3>Pitfalls to Avoid</h3><ol><li><strong>Missing Authentication</strong>: Unsecured channels expose your app to attacks.</li><li><strong>Ignoring Connection States</strong>: Users might see stale data without proper handling.</li><li><strong>Memory Leaks</strong>: Always close streams and disconnect Pusher when done.</li></ol><h3>Conclusion</h3><p>This implementation provides a robust foundation for real-time features in Flutter. By leveraging StreamController, GetX for state management, and Pusher’s authentication system, you can build scalable, secure real-time applications. Extend this further by:</p><ul><li>Adding presence channel support</li><li>Implementing retry logic for failed connections</li><li>Adding event filtering</li></ul><p><strong>Resources</strong>:</p><ul><li><a href="https://pusher.com/docs/channels">Pusher Channels Documentation</a></li><li><a href="https://pub.dev/packages/pusher_channels_flutter">pusher_channels_flutter Package</a></li></ul><p>By following this guide, you’ll be well-equipped to add real-time magic to your Flutter apps. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=891db932e431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient State Management in Flutter: Using ValueNotifier Instead of setState]]></title>
            <link>https://medium.com/@syedhasan.cse/efficient-state-management-in-flutter-using-valuenotifier-instead-of-setstate-e4d53e42d5df?source=rss-77a892bc9b3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4d53e42d5df</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Syed Mahamudul Hasan]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 14:43:51 GMT</pubDate>
            <atom:updated>2025-02-04T14:43:51.650Z</atom:updated>
            <content:encoded><![CDATA[<p>Using ValueNotifier Instead of setState in Flutter</p><p>When building Flutter applications, managing UI state efficiently is crucial for performance and maintainability. While setState is commonly used for updating the UI, it can lead to unnecessary widget rebuilds. An alternative approach is using ValueNotifier, which is both lightweight and reactive.</p><h3>What is ValueNotifier?</h3><p>ValueNotifier is a simple class in Flutter that extends ChangeNotifier. It allows you to manage a single value and notify listeners whenever the value changes. This makes it a great choice for updating specific parts of the UI without rebuilding the entire widget tree.</p><p>ValueNotifier is included in the Flutter framework and can be used by importing:</p><pre>import &#39;package:flutter/foundation.dart&#39;;</pre><p>ValueNotifier is a simple class in Flutter that extends ChangeNotifier. It allows you to manage a single value and notify listeners whenever the value changes. This makes it a great choice for updating specific parts of the UI without rebuilding the entire widget tree.</p><h3>Why Use ValueNotifier?</h3><ol><li>Efficiency: Only the widgets listening to the ValueNotifier rebuild when the value changes.</li><li>Simplicity: It’s easy to implement and does not require complex state management solutions.</li><li>Granular Control: Ideal for scenarios where you need to update specific UI components without affecting others.</li></ol><h3>How to Use ValueNotifier</h3><ol><li>Declare a ValueNotifier:</li></ol><pre>final ValueNotifier&lt;int&gt; counter = ValueNotifier&lt;int&gt;(0);</pre><ol><li>Wrap Widgets with ValueListenableBuilder:</li></ol><pre>ValueListenableBuilder&lt;int&gt;(<br>  valueListenable: counter,<br>  builder: (context, value, child) {<br>    return Text(<br>      &#39;Counter: $value&#39;,<br>      style: TextStyle(fontSize: 24),<br>    );<br>  },<br>),</pre><ol><li>Update the ValueNotifier:</li></ol><pre>ElevatedButton(<br>  onPressed: () {<br>    counter.value += 1;<br>  },<br>  child: Text(&#39;Increment&#39;),<br>)</pre><h3>Example: Counter App with ValueNotifier</h3><p>Here’s a complete example:</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>void main() =&gt; runApp(MyApp());</pre><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: CounterApp(),<br>    );<br>  }<br>}</pre><pre>class CounterApp extends StatelessWidget {<br>  final ValueNotifier&lt;int&gt; counter = ValueNotifier&lt;int&gt;(0);</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;ValueNotifier Example&#39;)),<br>      body: Center(<br>        child: ValueListenableBuilder&lt;int&gt;(<br>          valueListenable: counter,<br>          builder: (context, value, child) {<br>            return Text(<br>              &#39;Counter: $value&#39;,<br>              style: TextStyle(fontSize: 24),<br>            );<br>          },<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () =&gt; counter.value++,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><h3>When to Use ValueNotifier</h3><ul><li>Small, localized state changes (e.g., toggles, counters, loading indicators).</li><li>Situations where setState would unnecessarily rebuild a large portion of the widget tree.</li><li>Avoid using ValueNotifier for managing complex or global state; consider providers like Riverpod or Bloc instead.</li></ul><h3>Conclusion</h3><p>ValueNotifier offers a simple, efficient way to manage UI state in Flutter. By limiting widget rebuilds to only those listening to the notifier, it enhances performance and keeps your code clean. Try it out in your next Flutter project for better state management!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4d53e42d5df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>