<?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 Suraj Suryawanshi on Medium]]></title>
        <description><![CDATA[Stories by Suraj Suryawanshi on Medium]]></description>
        <link>https://medium.com/@suryawanshisuraj2681?source=rss-d634efc952bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q8I8DiNijcYk1JV25jA2pw.jpeg</url>
            <title>Stories by Suraj Suryawanshi on Medium</title>
            <link>https://medium.com/@suryawanshisuraj2681?source=rss-d634efc952bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:03:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suryawanshisuraj2681/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter Web and IFrame Communication]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/flutter-web-and-iframe-communication-4125edbe62f4?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4125edbe62f4</guid>
            <category><![CDATA[ifram]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 18:16:41 GMT</pubDate>
            <atom:updated>2026-10-22T18:16:41.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RaggjZJlMR11FwA6frQiQA.png" /></figure><p><em>Learn how a parent HTML website and a Flutter Web application can communicate with each other, with a complete working example.</em></p><h3>The Story: Two Applications, One Browser</h3><p>Imagine you’re building a banking portal.</p><p>The main website is developed using HTML, CSS, and JavaScript. It already has a navigation bar, a user profile, and several existing features. Now, your team wants to add a new feature developed using Flutter Web.</p><p>Instead of rebuilding the entire website, you decide to embed your Flutter application inside the existing website using an &lt;iframe&gt;.</p><p>Everything looks perfect. Your Flutter application loads successfully inside the website.</p><p>But then a new requirement arrives.</p><p>The parent website needs to send the logged-in user’s name to Flutter. When the user clicks a button inside Flutter, the parent website should receive a notification.</p><p>Suddenly, you realize that displaying an application inside another website is not the same as making them communicate.</p><p><strong>How can two applications running inside the same browser exchange information?</strong></p><p>The answer is window.postMessage().</p><p>In this article, we’ll understand how it works, why it’s useful, and how to implement communication between a parent HTML website and a Flutter Web application.</p><h3>1. What Is an IFrame?</h3><p>Before understanding communication, let’s understand the iframe itself.</p><p>An iframe, short for <em>inline frame</em>, allows you to display one webpage inside another webpage.</p><p>For example:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;My Website&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Welcome to My Website&lt;/h1&gt;<br>      &lt;iframe<br>        src=&quot;https://my-flutter-app.com&quot;<br>        width=&quot;100%&quot;<br>        height=&quot;500&quot;&gt;<br>      &lt;/iframe&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Here, the parent website displays the Flutter application inside an iframe.</p><p>Think of the parent website as a house and the iframe as a separate room inside it.</p><p>Both are visible on the same page, but the iframe has its own browser window context and document.</p><p>This separation is important. The parent website cannot freely access everything inside a cross-origin iframe, and the iframe cannot freely access everything in the parent website.</p><p>So, we need a communication mechanism.</p><h3>2. What Is Parent–IFrame Communication?</h3><p>Parent–iframe communication is the process of exchanging messages between the webpage that contains an iframe and the webpage loaded inside it.</p><p>There are two directions:</p><p><strong>Parent → IFrame</strong></p><p>The parent website sends information to the embedded Flutter application.</p><p>Examples:</p><ul><li>Send the user’s name.</li><li>Pass initial configuration.</li><li>Request navigation to a particular screen.</li><li>Notify Flutter about a change in the host application.</li></ul><p><strong>IFrame → Parent</strong></p><p>The Flutter application sends information back to the parent website.</p><p>Examples:</p><ul><li>Notify the website that a form was submitted.</li><li>Tell the website that initialization is complete.</li><li>Notify the website about an application event.</li><li>Request that the host website perform a supported action.</li></ul><p>The browser provides an API called postMessage() to support this communication, including between pages that have different origins.</p><h3>3. Understanding postMessage() in Simple Language</h3><p>Let’s start with a simple JavaScript example.</p><p>Imagine the parent website has an iframe:</p><pre>&lt;iframe<br>  id=&quot;flutterFrame&quot;<br>  src=&quot;https://flutter.example.com&quot;&gt;<br>&lt;/iframe&gt;</pre><p>The parent can send a message to the iframe like this:</p><pre>const iframe = document.getElementById(&quot;flutterFrame&quot;);<br>iframe.contentWindow.postMessage(<br>  &quot;Hello from the parent website!&quot;,<br>  &quot;https://flutter.example.com&quot;<br>);</pre><p>Let’s understand the important parts.</p><h4>iframe.contentWindow</h4><p>This gives us a reference to the browser window of the webpage loaded inside the iframe.</p><p>It is the target to which we want to send our message.</p><h4>postMessage()</h4><p>This sends a message to that window.</p><p>The receiving application must listen for the browser’s message event to process it.</p><h4>The target origin</h4><p>The second argument specifies which origin is allowed to receive the message.</p><p>In this example, the message is intended for <a href="https://flutter.example.com./">https://flutter.example.com.</a></p><p>Always specify the expected target origin instead of using &quot;*&quot; when sending sensitive or application-specific messages.</p><p>Now, one important question remains: how does the receiving application read the message?</p><p>It registers a message listener.</p><pre>window.addEventListener(&quot;message&quot;, (event) =&gt; {<br>  console.log(&quot;Received message:&quot;, event.data);<br>});</pre><p>The browser calls this listener when a message arrives.</p><p>The event.data property contains the message payload, while event.origin identifies the sender&#39;s origin.</p><p>This is the foundation of iframe communication.</p><h3>4. Our Practical Example</h3><p>Let’s build a small application in which the parent HTML website and Flutter Web communicate in both directions.</p><p>Our requirements are simple:</p><ol><li>The parent website contains a button called <strong>Send Username to Flutter</strong>.</li><li>Clicking the button sends a username to Flutter.</li><li>Flutter displays a personalized greeting.</li><li>Flutter sends an acknowledgement to the parent website.</li><li>Flutter also contains a button that sends a message to the parent.</li><li>The parent website displays that message.</li></ol><p>Our communication flow will look like this:</p><pre>Parent HTML Website<br>        |<br>        | 1. Sends username<br>        v<br>    postMessage()<br>        |<br>        v<br>Flutter Web Application<br>        |<br>        | 2. Updates the UI<br>        |<br>        | 3. Sends acknowledgement<br>        v<br>    postMessage()<br>        |<br>        v<br>Parent HTML Website</pre><p>We’ll use JSON strings for our messages so both sides follow a consistent format.</p><h3>5. Step One: Create the Flutter Application</h3><p>Create a new Flutter project:</p><pre>flutter create iframe_communication<br>cd iframe_communication<br>flutter pub add web</pre><p>The web package provides modern browser API bindings for Dart.</p><p>Our Flutter code will use package:web and dart:js_interop, rather than the older dart:html approach.</p><p>We’ll run the Flutter application on port 5000 and the parent website on port 8080.</p><p>For this example, both applications will run locally.</p><h3>6. Step Two: Write the Flutter Code</h3><p>Open lib/main.dart and replace its contents with the following code.</p><pre>import &#39;dart:convert&#39;;<br>import &#39;dart:js_interop&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:web/web.dart&#39; as web;<br>void main() {<br>  runApp(const CommunicationApp());<br>}<br>class CommunicationApp extends StatelessWidget {<br>  const CommunicationApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: CommunicationScreen(),<br>    );<br>  }<br>}<br>class CommunicationScreen extends StatefulWidget {<br>  const CommunicationScreen({super.key});<br>  @override<br>  State&lt;CommunicationScreen&gt; createState() =&gt;<br>      _CommunicationScreenState();<br>}<br>class _CommunicationScreenState<br>    extends State&lt;CommunicationScreen&gt; {<br>  // Origin of the parent HTML website.<br>  static const String parentOrigin =<br>      &#39;http://localhost:8080&#39;;<br>  String receivedMessage =<br>      &#39;Waiting for the parent website...&#39;;<br>  String status = &#39;Ready&#39;;<br>  late final JSFunction messageListener;<br>  @override<br>  void initState() {<br>    super.initState();<br>    // Convert the Dart callback into a JavaScript function.<br>    messageListener = _handleMessage.toJS;<br>    // Start listening for messages from the browser.<br>    web.window.addEventListener(<br>      &#39;message&#39;,<br>      messageListener,<br>    );<br>  }<br>  void _handleMessage(web.Event event) {<br>    final messageEvent = event as web.MessageEvent;<br>    // Accept messages only from our trusted parent origin.<br>    if (messageEvent.origin != parentOrigin) {<br>      return;<br>    }<br>    // This example expects the payload to be a JSON string.<br>    if (messageEvent.data is! JSString) {<br>      return;<br>    }<br>    try {<br>      final raw =<br>          (messageEvent.data as JSString).toDart;<br>      final data =<br>          jsonDecode(raw) as Map&lt;String, dynamic&gt;;<br>      if (data[&#39;action&#39;] == &#39;UPDATE_USER&#39;) {<br>        final username = data[&#39;username&#39;] as String?;<br>        if (username == null) return;<br>        setState(() {<br>          receivedMessage = &#39;Hello, $username!&#39;;<br>          status = &#39;Message received successfully&#39;;<br>        });<br>        // Send acknowledgement to the parent website.<br>        _sendToParent({<br>          &#39;action&#39;: &#39;MESSAGE_RECEIVED&#39;,<br>          &#39;message&#39;: &#39;Flutter received the username.&#39;,<br>        });<br>      }<br>    } on FormatException {<br>      // Ignore malformed JSON.<br>    } on TypeError {<br>      // Ignore unexpected data structures or types.<br>    }<br>  }<br>  void _sendToParent(<br>    Map&lt;String, dynamic&gt; payload,<br>  ) {<br>    web.window.parent.postMessage(<br>      jsonEncode(payload).toJS,<br>      parentOrigin.toJS,<br>    );<br>  }<br>  void _notifyParent() {<br>    _sendToParent({<br>      &#39;action&#39;: &#39;FLUTTER_BUTTON_CLICKED&#39;,<br>      &#39;message&#39;: &#39;The Flutter button was clicked!&#39;,<br>    });<br>    setState(() {<br>      status = &#39;Message sent to parent website&#39;;<br>    });<br>  }<br>  @override<br>  void dispose() {<br>    // Remove the listener when this widget is disposed.<br>    web.window.removeEventListener(<br>      &#39;message&#39;,<br>      messageListener,<br>    );<br>    super.dispose();<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Flutter IFrame App&#39;),<br>        backgroundColor: Colors.indigo,<br>        foregroundColor: Colors.white,<br>      ),<br>      body: Center(<br>        child: Padding(<br>          padding: const EdgeInsets.all(24),<br>          child: Column(<br>            mainAxisSize: MainAxisSize.min,<br>            children: [<br>              const Icon(<br>                Icons.web,<br>                size: 60,<br>                color: Colors.indigo,<br>              ),<br>              const SizedBox(height: 20),<br>              const Text(<br>                &#39;Message from parent:&#39;,<br>                style: TextStyle(<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              const SizedBox(height: 8),<br>              Text(<br>                receivedMessage,<br>                textAlign: TextAlign.center,<br>              ),<br>              const SizedBox(height: 12),<br>              Text(<br>                &#39;Status: $status&#39;,<br>                textAlign: TextAlign.center,<br>              ),<br>              const SizedBox(height: 24),<br>              ElevatedButton(<br>                onPressed: _notifyParent,<br>                child: const Text(<br>                  &#39;Send message to parent&#39;,<br>                ),<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Let’s Understand the Flutter Code</h3><p>Don’t worry if some of the browser-related code looks unfamiliar. Let’s break it down.</p><h4>A. Listening for messages</h4><pre>messageListener = _handleMessage.toJS;<br>web.window.addEventListener(<br>  &#39;message&#39;,<br>  messageListener,<br>);</pre><p>Flutter is running in a browser, so it can listen for browser events.</p><p>The message event is triggered when another window sends a message using postMessage().</p><p>The .toJS conversion makes our Dart callback usable as a JavaScript callback.</p><h4>B. Reading the message</h4><pre>final messageEvent = event as web.MessageEvent;<br>if (messageEvent.origin != parentOrigin) {<br>  return;<br>}</pre><p>The browser provides information about the sender.</p><p>We check its origin before processing the message. This matters because other websites may also attempt to send messages to an embedded application.</p><h4>C. Decoding JSON</h4><pre>final raw = (messageEvent.data as JSString).toDart;<br>final data =<br>    jsonDecode(raw) as Map&lt;String, dynamic&gt;;</pre><p>The parent sends a JSON string, such as:</p><pre>{<br>  &quot;action&quot;: &quot;UPDATE_USER&quot;,<br>  &quot;username&quot;: &quot;John&quot;<br>}</pre><p>Flutter converts that string into a Dart map and checks the action.</p><h4>D. Updating the UI</h4><pre>setState(() {<br>  receivedMessage = &#39;Hello, $username!&#39;;<br>});</pre><p>Once the message is received, Flutter updates the displayed text.</p><p>The parent website doesn’t directly modify the Flutter widget tree. Instead, it sends a message, and Flutter decides how to respond.</p><p>This separation is one of the most important ideas to understand.</p><h4>E. Sending a message back</h4><pre>web.window.parent.postMessage(<br>  jsonEncode(payload).toJS,<br>  parentOrigin.toJS,<br>);</pre><p>Here, window.parent refers to the webpage that contains our iframe.</p><p>The Flutter app sends a message to the parent, which can then process it using its own JavaScript listener.</p><h3>7. Step Three: Create the Parent HTML Website</h3><p>Create a separate directory named parent_site.</p><p>Inside it, create an index.html file.</p><p>This is the complete parent website:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta<br>    name=&quot;viewport&quot;<br>    content=&quot;width=device-width, initial-scale=1&quot;<br>  /&gt;<br>  &lt;title&gt;Parent Website&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>      font-family: Arial, sans-serif;<br>      margin: 30px;<br>      background: #f5f6fa;<br>    }<br>    .panel {<br>      max-width: 900px;<br>      margin: auto;<br>      background: white;<br>      padding: 24px;<br>      border-radius: 12px;<br>    }<br>    iframe {<br>      width: 100%;<br>      height: 450px;<br>      border: 1px solid #ddd;<br>      border-radius: 8px;<br>      background: white;<br>    }<br>    button {<br>      padding: 10px 16px;<br>      margin: 12px 0;<br>      cursor: pointer;<br>    }<br>    #messages {<br>      padding: 12px;<br>      background: #eef2ff;<br>      border-radius: 8px;<br>      min-height: 24px;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div class=&quot;panel&quot;&gt;<br>    &lt;h1&gt;Parent HTML Website&lt;/h1&gt;<br>    &lt;p&gt;<br>      This website embeds a Flutter Web application.<br>    &lt;/p&gt;<br>    &lt;button id=&quot;sendButton&quot;&gt;<br>      Send Username to Flutter<br>    &lt;/button&gt;<br>    &lt;iframe<br>      id=&quot;flutterFrame&quot;<br>      src=&quot;http://localhost:5000&quot;<br>      title=&quot;Flutter application&quot;&gt;<br>    &lt;/iframe&gt;<br>    &lt;h3&gt;Messages received from Flutter&lt;/h3&gt;<br>    &lt;div id=&quot;messages&quot;&gt;<br>      Waiting for Flutter...<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;script&gt;<br>    const FLUTTER_ORIGIN = &quot;http://localhost:5000&quot;;<br>    const flutterFrame =<br>      document.getElementById(&quot;flutterFrame&quot;);<br>    const messages =<br>      document.getElementById(&quot;messages&quot;);<br>    // Parent HTML -&gt; Flutter<br>    document<br>      .getElementById(&quot;sendButton&quot;)<br>      .addEventListener(&quot;click&quot;, () =&gt; {<br>        const payload = {<br>          action: &quot;UPDATE_USER&quot;,<br>          username: &quot;Suraj&quot;<br>        };<br>        flutterFrame.contentWindow.postMessage(<br>          JSON.stringify(payload),<br>          FLUTTER_ORIGIN<br>        );<br>      });<br>    // Flutter -&gt; Parent HTML<br>    window.addEventListener(&quot;message&quot;, (event) =&gt; {<br>      // Accept messages only from our Flutter app.<br>      if (event.origin !== FLUTTER_ORIGIN) {<br>        return;<br>      }<br>      if (typeof event.data !== &quot;string&quot;) {<br>        return;<br>      }<br>      try {<br>        const data = JSON.parse(event.data);<br>        if (data.action === &quot;MESSAGE_RECEIVED&quot;) {<br>          messages.textContent =<br>            &quot;Acknowledgement: &quot; + data.message;<br>        } else if (<br>          data.action === &quot;FLUTTER_BUTTON_CLICKED&quot;<br>        ) {<br>          messages.textContent =<br>            &quot;Flutter event: &quot; + data.message;<br>        }<br>      } catch {<br>        messages.textContent =<br>          &quot;Invalid message received.&quot;;<br>      }<br>    });<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Let’s Understand the HTML Code</h3><p><strong>A. Embedding Flutter</strong></p><pre>&lt;iframe<br>  id=&quot;flutterFrame&quot;<br>  src=&quot;http://localhost:5000&quot;&gt;<br>&lt;/iframe&gt;</pre><p>This loads the Flutter application inside the parent website.</p><p><strong>B. Sending a message to Flutter</strong></p><pre>flutterFrame.contentWindow.postMessage(<br>  JSON.stringify({<br>    action: &quot;UPDATE_USER&quot;,<br>    username: &quot;John&quot;<br>  }),<br>  FLUTTER_ORIGIN<br>);</pre><p>We use contentWindow to target the iframe&#39;s window and postMessage() to send our data.</p><p>JSON.stringify() converts the JavaScript object into a string, which our Flutter implementation expects.</p><p><strong>C. Receiving messages from Flutter</strong></p><pre>window.addEventListener(&quot;message&quot;, (event) =&gt; {<br>  if (event.origin !== FLUTTER_ORIGIN) {<br>    return;<br>  }<br>  const data = JSON.parse(event.data);<br>  console.log(data);<br>});</pre><p>This listener receives messages sent to the parent window.</p><p>The parent checks the origin and then processes the event based on its action.</p><h3>8. Step Four: Run the Application</h3><p>Let’s run both applications locally.</p><h4>Run Flutter Web</h4><p>Open a terminal inside the Flutter project:</p><pre>flutter run -d web-server --web-port 5000</pre><p>Keep the process running.</p><p>The Flutter app should now be accessible at:</p><p><a href="http://localhost:5000/">http://localhost:5000</a></p><h4>Run the Parent Website</h4><p>Open another terminal and navigate to the parent_site directory.</p><p>Run:</p><pre>python -m http.server 8080</pre><p>Now open the following address in your browser:</p><p><a href="http://localhost:8080/">http://localhost:8080</a></p><p>You should see the parent website with the Flutter application embedded inside it.</p><h4>Test Parent → Flutter</h4><p>Click <strong>Send Username to Flutter</strong>.</p><p>The Flutter application should display:</p><blockquote><em>Hello, John!</em></blockquote><p>The parent website should then display an acknowledgement from Flutter.</p><h4>Test Flutter → Parent</h4><p>Inside the Flutter application, click <strong>Send message to parent</strong>.</p><p>The parent website should display:</p><blockquote><em>Flutter event: The Flutter button was clicked!</em></blockquote><p>Congratulations! Your parent HTML website and Flutter Web application are communicating in both directions.</p><h3>9. Why Do We Need event.origin?</h3><p>This is one of the most important security concepts in iframe communication.</p><p>Suppose your Flutter application is embedded inside a trusted banking portal. Another website may also try to send a message to the Flutter application.</p><p>If your app accepts every incoming message without checking its origin, it may process data from an unexpected sender.</p><p>That’s why we use:</p><pre>if (event.origin !== FLUTTER_ORIGIN) {<br>  return;<br>}</pre><p>And in Flutter:</p><pre>if (messageEvent.origin != parentOrigin) {<br>  return;<br>}</pre><p>The origin contains the protocol, hostname, and port.</p><p>For example:</p><ul><li><a href="http://localhost:8080/">http://localhost:8080</a></li><li><a href="http://localhost:5000/">http://localhost:5000</a></li><li><a href="https://example.com/">https://example.com</a></li></ul><p>These are different origins.</p><p><strong>Remember:</strong> checking the origin is necessary, but it isn’t sufficient by itself. Validate the payload, reject unexpected actions, and avoid treating messages as proof of user identity or authorization.</p><p>Also, use exact target origins for outgoing messages. Avoid &quot;*&quot; when sending information that should only reach a trusted recipient.</p><h3>10. What If Flutter Sends a Message Before the Parent Is Ready?</h3><p>Another real-world problem is timing.</p><p>Imagine Flutter loads and sends an APP_READY event before the parent website has registered its message listener.</p><p>The parent may miss the event.</p><p>Similarly, the parent may send an initialization message before Flutter has installed its listener.</p><p>A common solution is a simple handshake:</p><ol><li>The parent installs its message listener.</li><li>Flutter installs its message listener.</li><li>Flutter sends an APP_READY event.</li><li>The parent sends initialization data after receiving APP_READY.</li><li>Flutter validates the message and initializes its application.</li></ol><p>For example, Flutter could send:</p><pre>_sendToParent({<br>  &#39;action&#39;: &#39;APP_READY&#39;,<br>});</pre><p>The parent can then respond:</p><pre>if (data.action === &quot;APP_READY&quot;) {<br>  flutterFrame.contentWindow.postMessage(<br>    JSON.stringify({<br>      action: &quot;INITIALIZE_APP&quot;,<br>      theme: &quot;light&quot;<br>    }),<br>    FLUTTER_ORIGIN<br>  );<br>}</pre><p>For a production application, both sides should validate the handshake messages and account for iframe reloads and timeouts. If readiness messages can be missed, add a controlled retry mechanism or an explicit request-response protocol.</p><h3>11. How Should We Structure This in a Real Flutter Application?</h3><p>In a small example, handling messages inside a widget is acceptable.</p><p>In a larger application, however, you should avoid placing all browser communication logic inside your UI.</p><p>A cleaner structure might look like this:</p><pre>lib/<br>├── communication/<br>│   ├── iframe_communication_service.dart<br>│   ├── iframe_message.dart<br>│   └── iframe_message_handler.dart<br>├── data/<br>├── domain/<br>└── presentation/</pre><p>The responsibilities would be:</p><p><strong>IframeCommunicationService</strong></p><ul><li>Register and remove the browser message listener.</li><li>Send messages to the parent.</li><li>Validate the sender’s origin.</li><li>Decode incoming messages.</li></ul><p><strong>IframeMessage</strong></p><ul><li>Define the supported event names.</li><li>Represent the message payloads in a predictable format.</li></ul><p><strong>IframeMessageHandler</strong></p><ul><li>Map incoming events to application actions.</li><li>Coordinate navigation, configuration, or other approved behavior.</li></ul><p><strong>Presentation layer</strong></p><ul><li>React to the resulting state changes.</li><li>Update widgets through Provider, BLoC, or another state management solution.</li></ul><p>For example, if the parent sends a NAVIGATE_TO message, Flutter should validate the destination against an explicit allowlist before navigating. It should never blindly trust an arbitrary URL received from the host page.</p><p>This design keeps browser-specific code separate from business logic and makes the integration easier to test.</p><h3>12. Common Mistakes to Avoid</h3><h4>Mistake 1: Assuming the iframe and parent share the same window</h4><p>They don’t. The iframe has its own window context.</p><p>Use window.parent from inside the iframe and iframe.contentWindow from the parent to target the other side.</p><h4>Mistake 2: Forgetting to register a listener</h4><p>Calling postMessage() doesn&#39;t automatically update Flutter&#39;s UI.</p><p>The receiving window must listen for the message event and process the incoming data.</p><h4>Mistake 3: Using the wrong origin</h4><p>If your Flutter code expects http://localhost:8080 but the parent runs on port 8081, the origin check will reject the message.</p><p>Always verify the exact origin, including protocol and port.</p><h4>Mistake 4: Sending different payload formats</h4><p>If one side sends a JavaScript object while the other side expects a JSON string, the receiving code may reject the message.</p><p>Define a shared message format and follow it consistently.</p><h4>Mistake 5: Assuming messages are synchronous</h4><p>postMessage() sends an asynchronous message. It doesn&#39;t wait for the other application to finish processing it.</p><p>If you need a response, define a request ID and response event, or implement a handshake protocol.</p><h4>Mistake 6: Trusting every incoming message</h4><p>Even after checking the origin, validate the payload and permitted actions. Do not expose sensitive data or privileged operations simply because a message came from a known page.</p><h3>Conclusion</h3><p>Embedding Flutter Web inside an existing HTML website is relatively straightforward with an iframe. The more interesting challenge is making both applications work together.</p><p>The browser’s window.postMessage() API provides a simple mechanism for two-way communication:</p><ul><li>The parent uses iframe.contentWindow.postMessage() to send messages to Flutter.</li><li>Flutter uses a browser message event listener to receive and process them.</li><li>Flutter uses window.parent.postMessage() to send messages back.</li><li>The parent uses its own message event listener to receive those messages.</li></ul><p>Once you understand this pattern, you can build much richer integrations, from passing configuration and handling navigation requests to notifying the host about completed workflows.</p><p>The key is to treat communication as a defined interface between two independent applications, not as direct access to each other’s internal state.</p><h3>Further Reading</h3><ul><li><a href="https://docs.flutter.dev/platform-integration/web/embedding-flutter-web">Flutter Web Embedding</a></li><li><a href="https://dart.dev/interop/js-interop">Dart JavaScript Interoperability</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage">MDN: </a><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage">Window.postMessage()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/message_event">MDN: The </a><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/message_event">message event</a></li></ul><p>Connect with me:</p><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4125edbe62f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Named Constructors in Dart/Flutter.]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/named-constructors-in-dart-flutter-989391efe08e?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/989391efe08e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[named-constructors]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 18:16:08 GMT</pubDate>
            <atom:updated>2026-07-10T18:16:08.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IB83WtouA4ClTGwGv20tAw.png" /></figure><p>A few weeks ago, while reviewing code in one of my Flutter projects, I came across something that completely threw me off.</p><p>I was comfortable with constructors like Person(&quot;John&quot;), so I thought I had a decent understanding of constructors in Dart. But then I saw code that looked like this:</p><pre>emit(ApiCallState.loading());<br>emit(ApiCallState.success(users));<br>emit(ApiCallState.failure(error));</pre><p>My first reaction was, <em>“Wait… are these methods? Static functions? Factory methods? Why are they being called like constructors?”</em></p><p>Then I opened the class and things became even more confusing.</p><pre>const ApiCallState.loading()<br>    : this._(status: ApiStatus.loading);</pre><p>There was a mysterious :. A private constructor named ._(). No constructor body. And somehow, all of this was considered perfectly normal Dart.</p><p>I spent the next hour reading the Dart documentation, experimenting with small examples, and eventually realized that I wasn’t confused about <strong>named constructors</strong> — I was missing the bigger picture of <strong>how constructors work in Dart</strong>.</p><p>If you’ve ever wondered what the difference is between an unnamed constructor, named parameters, named constructors, private constructors, and the initializer list, this article will connect all of those pieces together. By the end, that intimidating ApiCallState.loading() line will feel as natural as Person(&quot;John&quot;).</p><h3>What is a Constructor?</h3><p>A constructor is a special function whose job is to create an object.</p><p>Whenever you write</p><pre>Person(&quot;John&quot;);</pre><p>you’re asking Dart to create a new Person object.</p><p>For example,</p><pre>class Person {<br>  final String name;<br>  Person(this.name);<br>}</pre><p>Usage:</p><pre>final person = Person(&quot;John&quot;);</pre><p>The object created looks like:</p><pre>Person<br>------<br>name = &quot;John&quot;</pre><p>Every class can have one or more constructors.</p><h3>The Default (Unnamed) Constructor</h3><p>The most common constructor is the unnamed constructor.</p><pre>class Person {<br>  final String name;<br>  final int age;<br>  Person(this.name, this.age);<br>}</pre><p>Usage:</p><pre>final person = Person(&quot;John&quot;, 24);</pre><p>Notice something interesting.</p><p>The constructor has the same name as the class.</p><pre>Person(...)</pre><p>This is called the <strong>default</strong> or <strong>unnamed constructor</strong>.</p><h3>What is this.name?</h3><p>You might have noticed this syntax:</p><pre>Person(this.name, this.age);</pre><p>This is just a shorthand.</p><p>Instead of writing</p><pre>class Person {<br>  final String name;<br>  final int age;<br>  Person(String name, int age)<br>      : name = name,<br>        age = age;<br>}</pre><p>Dart allows us to write</p><pre>Person(this.name, this.age);</pre><p>Much cleaner.</p><h3>Optional Parameters</h3><p>Sometimes not every value is required.</p><p>Instead of positional parameters, Dart allows named parameters using curly braces.</p><pre>class Person {<br>  final String name;<br>  final int age;<br>  Person({<br>    required this.name,<br>    required this.age,<br>  });<br>}</pre><p>Usage:</p><pre>Person(<br>  name: &quot;John&quot;,<br>  age: 24,<br>);</pre><p>This is often called <strong>named parameters</strong>.</p><p>Notice the difference.</p><p>Positional:</p><pre>Person(&quot;John&quot;, 24);</pre><p>Named:</p><pre>Person(<br>  name: &quot;John&quot;,<br>  age: 24,<br>);</pre><p>Named parameters improve readability because the meaning of each value is immediately obvious.</p><h3>Default Values</h3><p>Named parameters can also have default values.</p><pre>class Person {<br>  final String name;<br>  final bool isEmployee;<br>  Person({<br>    required this.name,<br>    this.isEmployee = false,<br>  });<br>}</pre><p>Now you can simply write</p><pre>Person(name: &quot;John&quot;);</pre><p>and</p><pre>isEmployee = false</pre><p>is automatically assigned.</p><h3>Multiple Constructors</h3><p>Now suppose your application has two kinds of users.</p><p>A normal user.</p><pre>Person(&quot;John&quot;);</pre><p>And a guest user.</p><p>Instead of doing</p><pre>Person(&quot;Guest&quot;);</pre><p>everywhere, we can create another constructor.</p><pre>class Person {<br>  final String name;<br>  Person(this.name);<br>  Person.guest() : name = &quot;Guest&quot;;<br>}</pre><p>Usage:</p><pre>Person(&quot;John&quot;);<br>Person.guest();</pre><p>Notice something new.</p><pre>Person.guest()</pre><p>This is called a <strong>named constructor</strong>.</p><h3>Why Are They Called Named Constructors?</h3><p>Because unlike the default constructor,</p><pre>Person(...)</pre><p>they have an additional name.</p><pre>Person.guest()<br>Person.admin()<br>Person.employee()</pre><p>Each constructor creates the object in a different way.</p><h3>A Real Example</h3><p>Imagine an e-commerce app.</p><p>Instead of writing</p><pre>User(<br>  role: &quot;Admin&quot;,<br>  canDeleteUsers: true,<br>  canEditProducts: true,<br>);</pre><p>every time,</p><p>we can write</p><pre>class User {<br>  final String role;<br>  final bool canDeleteUsers;<br>  final bool canEditProducts;<br><br>  User({<br>    required this.role,<br>    required this.canDeleteUsers,<br>    required this.canEditProducts,<br>  });<br><br>  User.admin()<br>      : role = &quot;Admin&quot;,<br>        canDeleteUsers = true,<br>        canEditProducts = true;<br><br>  User.customer()<br>      : role = &quot;Customer&quot;,<br>        canDeleteUsers = false,<br>        canEditProducts = false;<br>}</pre><p>Usage:</p><pre>User.admin();<br>User.customer();</pre><p>The intent becomes crystal clear.</p><h3>Introducing the Initializer List</h3><p>Now let’s talk about this strange syntax.</p><pre>Person.guest()<br>    : name = &quot;Guest&quot;;</pre><p>What is this colon?</p><p>This is called the <strong>initializer list</strong>.</p><p>It runs <strong>before</strong> the constructor body.</p><p>Instead of</p><pre>Person.guest() {<br>  name = &quot;Guest&quot;;<br>}</pre><p>(which won’t work because name is final)</p><p>we initialize the field before the object is fully created.</p><pre>Person.guest()<br>    : name = &quot;Guest&quot;;</pre><p>The initializer list is commonly used to initialize final fields.</p><h3>Calling Another Constructor</h3><p>Now consider this class.</p><pre>class Person {<br>  final String name;<br>  final int age;<br>  Person._({<br>    required this.name,<br>    required this.age,<br>  });<br><br>  Person.guest()<br>      : this._(<br>          name: &quot;Guest&quot;,<br>          age: 0,<br>        );<br>}</pre><p>Instead of initializing fields directly,</p><p>the initializer list calls another constructor.</p><pre>Person.guest()<br>     ↓<br>Person._(<br>    name: &quot;Guest&quot;,<br>    age: 0,<br>)</pre><p>This is known as a <strong>redirecting constructor</strong>.</p><h3>Why Use a Private Constructor?</h3><p>Suppose we have this class.</p><pre>class ApiCallState&lt;T&gt; {<br>  final ApiStatus status;<br>  final T? data;<br>  final String? errorMessage;<br>  const ApiCallState._({<br>    required this.status,<br>    this.data,<br>    this.errorMessage,<br>  });<br>}</pre><p>The private constructor can create every possible combination.</p><pre>ApiCallState._(<br>  status: ApiStatus.loading,<br>  data: user,<br>);</pre><p>But this doesn’t make sense.</p><p>A loading state shouldn’t already have data.</p><p>Similarly,</p><pre>ApiCallState._(<br>  status: ApiStatus.success,<br>);</pre><p>A success state without data is also invalid.</p><p>The constructor is too flexible.</p><h3>Named Constructors to the Rescue</h3><p>Instead of exposing the private constructor,</p><p>we expose only valid states.</p><pre>const ApiCallState.idle()<br>    : this._(<br>        status: ApiStatus.idle,<br>      );<br><br>const ApiCallState.loading()<br>    : this._(<br>        status: ApiStatus.loading,<br>      );<br><br>const ApiCallState.success(T data)<br>    : this._(<br>        status: ApiStatus.success,<br>        data: data,<br>      );<br><br>const ApiCallState.failure(String message)<br>    : this._(<br>        status: ApiStatus.failure,<br>        errorMessage: message,<br>      );</pre><p>Now creating states becomes extremely expressive.</p><pre>emit(ApiCallState.loading());<br>emit(ApiCallState.success(users));<br>emit(ApiCallState.failure(error));</pre><p>You immediately understand what’s happening.</p><h3>Could We Use One Constructor Instead?</h3><p>Absolutely.</p><p>We could write</p><pre>ApiCallState({<br>  required this.status,<br>  this.data,<br>  this.errorMessage,<br>});</pre><p>and use</p><pre>ApiCallState(<br>  status: ApiStatus.success,<br>  data: users,<br>);</pre><p>It works.</p><p>But now this also works.</p><pre>ApiCallState(<br>  status: ApiStatus.success,<br>);</pre><p>Success without data.</p><p>Or</p><pre>ApiCallState(<br>  status: ApiStatus.loading,<br>  data: users,<br>);</pre><p>Loading with data.</p><p>Or</p><pre>ApiCallState(<br>  status: ApiStatus.failure,<br>  data: users,<br>  errorMessage: &quot;Network Error&quot;,<br>);</pre><p>Failure with both data and an error.</p><p>These invalid states are easy to create accidentally.</p><h3>Named Constructors as an API Design Tool</h3><p>Many beginners think named constructors exist only for convenience.</p><p>In reality, they are a way to <strong>design better APIs</strong>.</p><p>Instead of allowing developers to create any object,</p><p>you expose only meaningful ways to create one.</p><p>Compare these two approaches.</p><p>Generic constructor:</p><pre>ApiCallState(<br>  status: ApiStatus.success,<br>  data: users,<br>);</pre><p>Named constructor:</p><pre>ApiCallState.success(users);</pre><p>Which one is easier to read?</p><p>Which one is harder to misuse?</p><p>The answer becomes obvious as your project grows.</p><h3>When Should You Use Named Constructors?</h3><p>Named constructors are a great choice when:</p><ul><li>Your class has multiple valid ways to be created.</li><li>You want constructor names to describe intent (guest, admin, success, failure).</li><li>You want to prevent invalid object states.</li><li>You want cleaner, more readable code.</li></ul><h3>Key Takeaways</h3><ul><li>Every Dart class can have one unnamed constructor and multiple named constructors.</li><li>Curly braces ({}) in constructor parameters define <strong>named parameters</strong>, improving readability.</li><li>this.name is shorthand for assigning constructor parameters to class fields.</li><li>The <strong>initializer list</strong> (:) runs before the constructor body and is commonly used to initialize final fields.</li><li>The initializer list can also <strong>redirect to another constructor</strong> using this(...) or this.named(...).</li><li>A <strong>private constructor</strong> (e.g., Class._()) centralizes object initialization while keeping implementation details hidden.</li><li>Named constructors are not just syntax — they’re an API design tool that makes code more expressive and helps prevent invalid object states.</li></ul><p>When I first saw ApiCallState.success(data) in a production codebase, I assumed it was just a stylistic preference. After digging deeper, I realized it represents a broader design philosophy: <strong>make the correct way the easiest way</strong>. Named constructors, private constructors, and initializer lists work together to create APIs that are not only easier to read, but also much harder to misuse. That&#39;s why you&#39;ll see this pattern throughout well-written Flutter and Dart projects.</p><p>Connect with me:</p><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=989391efe08e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ever thought what is CanvasKit, Wasm in flutter web?]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/ever-thought-what-is-canvaskit-wasm-in-flutter-web-47b3884d05b7?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/47b3884d05b7</guid>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 17:40:40 GMT</pubDate>
            <atom:updated>2026-06-28T17:40:40.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ph1NVwTTzWZb9xaQRTE7jQ.png" /></figure><p><em>If you’ve been working with Flutter for some time, chances are you’ve heard senior developers casually mention terms like </em><strong><em>CanvasKit</em></strong><em>, </em><strong><em>Wasm</em></strong><em>, </em><strong><em>Skia </em></strong><em>while discussing Flutter Web performance.</em></p><p>At first, these terms can sound intimidating.</p><p>Questions such as:</p><ul><li><em>What is canvasKit and why do we need it?</em></li><li><em>What is WebAssembly?</em></li><li>Are they related?</li><li><em>What exactly does Skia do?</em></li><li><em>Why they are needed for web and not for android/iOS?</em></li></ul><p>are extremely common.</p><p>Let’s break down Flutter’s rendering architecture from first principles.</p><h3>The Big Picture: How Flutter Renders UI</h3><p>Suppose you write the following Flutter widget:</p><pre>Container(<br>  width: 100,<br>  height: 100,<br>  color: Colors.red,<br>)</pre><p>Flutter cannot directly display this widget on the screen.</p><p>Instead, rendering happens in multiple stages:</p><pre>Flutter Widgets<br>       ↓<br>Flutter Framework<br>       ↓<br>Flutter Engine<br>       ↓<br>Graphics Engine (Skia/Impeller)<br>       ↓<br>Platform Graphics API (OpenGL,Vulkan,Metal)<br>       ↓<br>GPU<br>       ↓<br>Screen</pre><p>Every layer has a specific responsibility.</p><h3>What Exactly is Skia?</h3><p><strong>Skia</strong> is Google’s 2D graphics engine written in C++.</p><p>Flutter uses Skia to render almost everything:</p><ul><li>Text</li><li>Shapes</li><li>Shadows</li><li>Images</li><li>Animations</li><li>CustomPaint widgets</li></ul><p>Skia is not unique to Flutter.</p><p>It is also used in:</p><ul><li>Google Chrome</li><li>Android</li><li>ChromeOS</li><li>Firefox (partially)</li><li>Android System UI</li></ul><p>Think of Skia as a highly optimized graphics library.</p><p>When Flutter wants to display something, it eventually asks Skia to draw it.</p><p>Conceptually:</p><pre>Flutter:<br>Text(&quot;Hello&quot;)<br>     ↓<br>Skia:<br>Draw text &quot;Hello&quot;<br>Font size: 20<br>Position: (100, 50)</pre><h3>Does Skia Actually Draw Pixels?</h3><p>The answer is <strong>yes, but not always directly</strong>.</p><p>Skia supports two rendering modes:</p><h3>1. Software Rendering (CPU)</h3><p>In software rendering, Skia computes every pixel itself.</p><p>Conceptually:</p><pre>For every pixel inside rectangle:<br>    Set color = Red</pre><p>This is CPU-intensive and generally slower.</p><h3>2. GPU Rendering (Most Common)</h3><p>Modern Flutter applications usually use GPU rendering.</p><p>In this mode, Skia does not manually calculate every pixel.</p><p>Instead, Skia generates drawing commands and sends them to the GPU.</p><p>For example:</p><pre>Draw rectangle<br>Position: x=10, y=20<br>Width: 100<br>Height: 100<br>Color: Red</pre><p>The GPU then performs the actual rasterization.</p><p>This is significantly faster because GPUs are specifically designed for parallel graphics processing.</p><h3>Then What Does the GPU Actually Do?</h3><p>GPUs are specialized processors optimized for rendering millions of pixels simultaneously.</p><p>Unlike CPUs, GPUs can process many graphics operations in parallel.</p><p>Responsibilities of the GPU include:</p><ul><li>Rasterizing shapes</li><li>Applying gradients</li><li>Rendering shadows</li><li>Running shaders</li><li>Scaling images</li><li>Drawing textures</li><li>Compositing layers</li></ul><p>Without GPUs, modern UIs and animations would be much slower.</p><h3>What are OpenGL, Vulkan, Metal, and DirectX?</h3><p>One common misconception is that applications communicate directly with the GPU.</p><p>They don’t.</p><p>Applications use <strong>graphics APIs</strong>.</p><p>Examples include:</p><pre>Platform              Graphics API<br>---------------------------------------------<br>Android               OpenGL ES,Vulkan<br>iOS/macOS             Metal<br>Windows               DirectX<br>Linux                 OpenGL, Vulkan</pre><p>These APIs act as translators between software and hardware.</p><p>The rendering pipeline on Android/iOS/Windows looks like:</p><pre>Android              iOS            Windows<br>------------------------------------------------------<br>Flutter             Flutter         Flutter<br>   ↓                 ↓               ↓<br>Skia                Skia            Skia<br>   ↓                 ↓               ↓<br>Vulkan/OpenGL       Metal           DirectX/OpenGL<br>   ↓                 ↓                ↓<br>GPU                 GPU             GPU</pre><p>You can think of these APIs as drivers or communication protocols that allow software to instruct the GPU.</p><h3>How Does Flutter Render on Mobile and Desktop?</h3><p>Traditionally, Flutter uses native Skia libraries.</p><pre>Flutter Framework<br>        ↓<br>Skia (native C++)<br>        ↓<br>OpenGL/Vulkan/Metal/DirectX<br>        ↓<br>GPU</pre><p>Since Android, iOS, Windows, Linux, and macOS can run native C++ code, Flutter simply ships Skia as a native library.</p><h3>What Changes on the Web?</h3><p>This is where many developers get confused.</p><p>Browsers cannot execute native C++ code directly.</p><p>For security and portability reasons, browsers can primarily execute:</p><ul><li>JavaScript</li><li>WebAssembly (Wasm)</li></ul><p>Since Skia is written in C++, it cannot run inside browsers as-is.</p><p>Therefore Flutter compiles Skia into WebAssembly.</p><pre>Skia (C++)<br>      ↓<br>Compiled to WebAssembly<br>      ↓<br>Executed by Browser</pre><p>This browser version of Skia is known as <strong>CanvasKit</strong>.</p><h3>Is CanvasKit a Separate Rendering Engine?</h3><p>No.</p><p>CanvasKit is <strong>not a separate rendering engine</strong>.</p><p>CanvasKit is essentially:</p><pre>Skia + WebAssembly + Browser Bindings</pre><p>In other words:</p><blockquote><em>CanvasKit is Skia running inside the browser.</em></blockquote><p>This is why Flutter applications rendered using CanvasKit look very similar across Android, iOS, desktop, and web.</p><h3>How browser communicates with GPU?</h3><p>On native platforms:</p><pre>Flutter<br>   ↓<br>Skia<br>   ↓<br>Vulkan/OpenGL/Metal<br>   ↓<br>GPU</pre><p>On the web:</p><pre>Flutter<br>   ↓<br>CanvasKit (Skia compiled to Wasm as browser can&#39;t run c++ version of skia)<br>   ↓<br>WebGL/WebGPU<br>   ↓<br>GPU</pre><p>The browser exposes graphics capabilities through APIs such as:</p><ul><li>WebGL</li><li>WebGPU</li></ul><p>CanvasKit ultimately uses these browser APIs to access the GPU.</p><p>Therefore Flutter Web still benefits from hardware acceleration.</p><h3>What Exactly is WebAssembly (Wasm)?</h3><p>WebAssembly is a low-level binary instruction format designed for the web.</p><p>It allows languages such as:</p><ul><li>C++</li><li>Rust</li><li>C#</li><li>Dart</li></ul><p>to run efficiently inside browsers.</p><p>Think of Wasm as:</p><blockquote><em>A portable, near-native execution format supported by modern browsers.</em></blockquote><p>Browsers contain runtimes capable of executing both JavaScript and WebAssembly.</p><h3>Is canvasKit is just skia compiled to wasm or something else?</h3><blockquote><strong><em>CanvasKit is more than just the </em></strong><strong><em>.wasm file, but the Wasm code is the core part of CanvasKit.</em></strong></blockquote><p>A more accurate definition is:</p><pre>CanvasKit = Skia compiled to Wasm + JavaScript bindings/API + browser integration code</pre><p>Let’s break it down.</p><h4>If you start with native Skia:</h4><pre>Skia (C++ source code)</pre><p>When building CanvasKit, Google compiles Skia using Emscripten:</p><pre>Skia (C++)<br>      ↓<br>Emscripten<br>      ↓<br>canvaskit.wasm</pre><p>This produces the WebAssembly binary.</p><p>However, Flutter cannot directly call functions inside a .wasm file. Some glue code is needed.</p><p>So CanvasKit also includes JavaScript wrappers:</p><pre>CanvasKit.MakeCanvasSurface(...)<br>CanvasKit.Color(...)<br>CanvasKit.Paint(...)</pre><p>These wrappers:</p><ul><li>load the .wasm file,</li><li>expose convenient APIs,</li><li>connect Skia with browser features like &lt;canvas&gt; and WebGL.</li></ul><p>So the actual CanvasKit package looks conceptually like:</p><pre>CanvasKit<br>│<br>├── canvaskit.wasm        ← compiled Skia engine<br>├── canvaskit.js          ← JS glue/bindings<br>└── browser integration   ← canvas, WebGL setup, etc.</pre><p>Therefore:</p><ul><li>Saying <strong>“CanvasKit is Skia compiled to Wasm”</strong> is mostly correct in everyday Flutter discussions.</li><li>Technically, <strong>the Wasm file itself is only one part of CanvasKit</strong>.</li><li>The term <strong>CanvasKit</strong> usually refers to the entire web package that allows Skia to run inside the browser.</li></ul><p>An analogy:</p><pre>Skia (C++) = car engine<br>canvaskit.wasm = engine installed in a car<br>canvaskit.js + browser bindings = steering wheel, pedals, dashboard<br>Entire car = CanvasKit</pre><p>So if someone says:</p><blockquote><em>“Flutter Web uses CanvasKit”</em></blockquote><p>they mean:</p><blockquote><em>“Flutter Web uses the CanvasKit package, whose core is Skia compiled to WebAssembly.”</em></blockquote><p>And if you inspect a Flutter web build using CanvasKit, you’ll typically see files similar to:</p><pre>canvaskit/<br>├── canvaskit.js<br>└── canvaskit.wasm</pre><p>where canvaskit.wasm contains the actual compiled Skia engine.</p><h3>How Did Flutter Web Originally Work?</h3><p>Historically, Flutter Web used the following architecture:</p><pre>Flutter App (Dart)                              Skia<br>          ↓                                      ↓<br>Compiled to JavaScript                   Compiled to WebAssembly</pre><p>At runtime:</p><pre>JavaScript<br>     ↓<br>Calls CanvasKit APIs<br>     ↓<br>CanvasKit (Wasm)<br>     ↓<br>WebGL<br>     ↓<br>GPU</pre><p>Notice something important:</p><p><strong>Skia never executes Flutter code.</strong></p><p>Flutter code and Skia are independent components.</p><p>Flutter simply sends drawing instructions to Skia.</p><h3>Can Flutter Code Also Be Compiled to Wasm?</h3><p>Yes.</p><p>Modern Flutter versions support:</p><pre>flutter build web --wasm</pre><p>In this architecture:</p><pre>Flutter App (Dart)                              Skia<br>          ↓                                      ↓<br>Compiled to WebAssembly                   Compiled to WebAssembly</pre><p>Both application code and rendering code run as Wasm modules.</p><h3>Does Compiling Flutter to Wasm Improve Performance?</h3><p>Potentially, yes.</p><p>Benefits may include:</p><ul><li>Faster CPU-intensive computations</li><li>Reduced JavaScript ↔ Wasm communication overhead</li><li>Better support for multithreading</li><li>Improved rendering efficiency on modern browsers</li></ul><p>However, for typical CRUD applications, users may not notice dramatic differences.</p><p>Performance improvements become more noticeable in:</p><ul><li>Graphics-heavy applications</li><li>Large applications</li><li>Complex animations</li><li>Image processing</li><li>Data-intensive workloads</li></ul><h3>Final Thoughts</h3><p>Whenever you hear someone say:</p><blockquote><em>“Flutter Web uses CanvasKit and Wasm”</em></blockquote><p>what they really mean is:</p><pre>Flutter UI<br>     ↓<br>Skia compiled to<br>     ↓<br>WebAssembly<br>     ↓<br>Browser Graphics APIs<br>     ↓<br>GPU</pre><p>The key takeaway is:</p><ul><li><strong>Skia</strong> is Flutter’s graphics engine.</li><li><strong>CanvasKit</strong> is Skia compiled for the web.</li><li><strong>WebAssembly</strong> allows native code like Skia to run in browsers.</li><li><strong>GPUs</strong> perform the heavy rendering work.</li><li><strong>OpenGL, Vulkan, Metal, WebGL, and DirectX</strong> are APIs used to communicate with GPUs.</li></ul><p>Understanding these layers makes many Flutter Web discussions much easier to follow and helps explain why Flutter behaves differently across mobile, desktop, and web platforms.</p><p>Connect with me:</p><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47b3884d05b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Provider Deep Dive: Understanding BuildContext, Provider Scope]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/flutter-provider-deep-dive-understanding-buildcontext-provider-scope-06ffafa4f864?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/06ffafa4f864</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 18:15:18 GMT</pubDate>
            <atom:updated>2026-06-14T18:15:18.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBubzerFORn3DJxzvrImNQ.png" /></figure><h3>Most articles explain Provider by saying:</h3><blockquote><em>“Provider must be above the widget.”</em></blockquote><p>While technically correct, that explanation is incomplete.</p><p>The real question is:</p><blockquote><em>What exactly does “above” mean?</em></blockquote><p>Understanding that single concept explains:</p><ul><li>Why ProviderNotFoundException happens</li><li>Why Builder sometimes magically fixes it</li><li>Why context.read() works in one widget but fails in another</li><li>Why providers don’t automatically work across routes</li><li>Why ChangeNotifierProvider.value() must be used during navigation</li></ul><p>Let’s start with the most confusing example.</p><h3>Example 1: Why Does This Throw ProviderNotFoundException?</h3><p>Consider the following code:</p><pre>class Screen1 extends StatelessWidget {<br>  const Screen1({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return ChangeNotifierProvider&lt;Screen1Provider&gt;(<br>      create: (BuildContext context) {<br>        return Screen1Provider();<br>      },<br>      child: Scaffold(<br>        appBar: AppBar(title: const Text(&#39;Screen 1&#39;)),<br>        body: Center(<br>          child: Column(<br>            mainAxisAlignment: MainAxisAlignment.center,<br>            children: [<br>              Text(<br>                context.read&lt;Screen1Provider&gt;().email,<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>This crashes with:</p><pre>ProviderNotFoundException<br>Error: Could not find the correct Provider&lt;Screen1Provider&gt; above this Screen1 Widget</pre><p>Most developers are surprised because they can clearly see the provider.</p><pre>Screen1<br>└── ChangeNotifierProvider</pre><p>So why can’t Flutter find it?</p><p>The answer lies in which BuildContext is being used.</p><h3>The Hidden Widget Tree</h3><p>The widget hierarchy looks like this:</p><pre>Screen1<br>└── ChangeNotifierProvider<br>    └── Scaffold<br>        └── Center<br>            └── Column<br>                └── Text</pre><p>Now let’s identify which context is being used.</p><pre>Widget build(BuildContext context)</pre><p>This context belongs to:</p><pre>Screen1</pre><p>not:</p><pre>ChangeNotifierProvider</pre><p>Visualized:</p><pre>Screen1  ← context belongs here (build(BuildContext context))<br>└── ChangeNotifierProvider<br>    └── Scaffold</pre><p>When Flutter executes:</p><pre>context.read&lt;Screen1Provider&gt;()</pre><p>Provider starts searching from the widget associated with that context.(or from the build method or builder which is responsible for creating new subTree with context).</p><pre>Screen1</pre><p>Provider then walks upward looking for a provider.</p><pre>MaterialApp<br>└── Navigator<br>    └── MaterialPageRoute<br>        └── Screen1  ← search starts here</pre><p>Notice what happened.</p><p>The search never entered the provider subtree.</p><p>Because the provider is below Screen1, not above it.</p><p>Provider only searches ancestors, never descendants.</p><p>Therefore Flutter throws:</p><pre>ProviderNotFoundException</pre><h3>Example 2: Why Does Builder Fix It?</h3><p>Now consider this version:</p><pre>class Screen1 extends StatelessWidget {<br>  const Screen1({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return ChangeNotifierProvider&lt;Screen1Provider&gt;(<br>      create: (BuildContext context) {<br>        return Screen1Provider();<br>      },<br>      child: Builder(<br>        builder: (context) {<br>          return Scaffold(<br>            appBar: AppBar(title: const Text(&#39;Screen 1&#39;)),<br>            body: Center(<br>              child: Column(<br>                mainAxisAlignment: MainAxisAlignment.center,<br>                children: [<br>                  Text(<br>                    context.read&lt;Screen1Provider&gt;().email,<br>                  ),<br>                ],<br>              ),<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>This works perfectly.</p><p>Why?</p><p>Because Builder creates a new BuildContext.</p><p>The hierarchy becomes:</p><pre>Screen1<br>└── ChangeNotifierProvider<br>    └── Builder  ← new context belongs here<br>        └── Scaffold<br>            └── Center<br>                └── Column<br>                    └── Text</pre><p>Now when Flutter executes:</p><pre>context.read&lt;Screen1Provider&gt;()</pre><p>the context belongs to Builder.</p><p>Visualized:</p><pre>Screen1<br>└── ChangeNotifierProvider<br>    └── Builder ← context<br>        └── Scaffold</pre><p>Provider searches upward:</p><pre>ChangeNotifierProvider<br>└── Builder(Found)</pre><p>Success.</p><p>No exception.</p><h3>The Golden Rule</h3><p>A provider can only be accessed by contexts that are descendants of that provider.</p><p>Think of it like this:</p><pre>Provider<br>└── Widget A<br>    └── Widget B<br>        └── Widget C</pre><p>Widget A, B, and C can access the provider.</p><p>But the parent of Provider cannot.</p><pre>Parent Widget<br>└── Provider</pre><p>The parent widget has no access because the provider is below it.</p><h3>How context.read() Actually Works</h3><p>When you write:</p><pre>context.read&lt;MyProvider&gt;()</pre><p>Provider:</p><ol><li>Takes the BuildContext</li><li>Finds the widget associated with it</li><li>Walks upward through ancestors</li><li>Returns the first matching provider</li></ol><p>Conceptually:</p><pre>Provider<br>└── Widget A<br>    └── Widget B<br>        └── Widget C ← context</pre><p>Search path:</p><pre>Provider  (Found)<br>↑<br>Widget A<br>↑<br>Widget B<br>↑<br>Widget C</pre><p>Provider found.</p><h3>Conditions Required For context.read() To Work</h3><p>Two conditions must be true.</p><h3>Condition 1</h3><p>The provider must be an ancestor of the context.</p><pre>Provider<br>└── ChildWidget</pre><p>Works.</p><pre>ParentWidget<br>└── Provider</pre><p>Fails.</p><h3>Condition 2</h3><p>The BuildContext must belong to that subtree.</p><p>This becomes important when navigating between routes.</p><h3>read(), watch(), and Consumer</h3><h3>read()</h3><pre>context.read&lt;MyProvider&gt;()</pre><ul><li>Access state</li><li>No rebuild</li></ul><p>Typical use:</p><pre>onPressed: () {<br>  context.read&lt;AuthProvider&gt;().login();<br>}</pre><h3>watch()</h3><pre>context.watch&lt;MyProvider&gt;()</pre><ul><li>Access state</li><li>Rebuild when notifyListeners() runs</li></ul><h3>Consumer</h3><pre>Consumer&lt;AuthProvider&gt;(<br>  builder: (_, provider, __) {<br>    return Text(provider.username);<br>  },<br>)</pre><p>Same rebuild behavior as watch() but allows rebuilding a smaller subtree.</p><h3>Why Providers Don’t Automatically Work Across Routes</h3><p>Consider:</p><pre>Route 1<br>└── ChangeNotifierProvider<br>    └── Screen1</pre><p>Inside Screen1:</p><pre>context.read&lt;LoginProvider&gt;()</pre><p>works.</p><p>Now push another route:</p><pre>Navigator.push(<br>  context,<br>  MaterialPageRoute(<br>    builder: (_) =&gt; const Screen2(),<br>  ),<br>);</pre><p>Flutter creates:</p><pre>Route 1<br>└── ChangeNotifierProvider<br>    └── Screen1</pre><pre>Route 2<br>└── Screen2</pre><p>Notice something important.</p><p>Screen2 is not a child of Screen1.</p><p>Screen2 belongs to an entirely different route subtree.</p><p>Therefore:</p><pre>context.read&lt;LoginProvider&gt;()</pre><p>inside Screen2 fails.</p><p>Not because the provider disappeared.</p><p>Not because the provider was disposed.</p><p>But because Screen2’s context is outside that provider’s subtree.</p><h3>Sharing State Between Routes</h3><p>Suppose Screen1 contains a login form.</p><p>After submission:</p><pre>Screen1<br>└── Submit<br>    └── Screen2</pre><p>Screen2 must:</p><ul><li>Display errors</li><li>Retry API calls</li><li>Access the same login state</li></ul><p>For that, Screen2 must receive the existing provider instance.</p><h3>The Correct Solution: ChangeNotifierProvider.value</h3><p>Wrap the new route while navigating.</p><pre>Navigator.push(<br>  context,<br>  MaterialPageRoute(<br>    builder: (_) =&gt; ChangeNotifierProvider.value(<br>      value: context.read&lt;LoginProvider&gt;(),<br>      child: const Screen2(),<br>    ),<br>  ),<br>);</pre><p>Result:</p><pre>Route 1<br>└── Provider(LoginProvider)<br>    └── Screen1</pre><pre>Route 2<br>└── Provider.value(LoginProvider)<br>    └── Screen2</pre><p>Both routes now share the exact same LoginProvider instance.</p><p>No duplication.</p><p>No recreation.</p><p>Just a shared reference.</p><h3>Why Adding .value Inside Screen2 Does NOT Work</h3><p>Many developers try this:</p><pre>class Screen2 extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return ChangeNotifierProvider.value(<br>      value: context.read&lt;LoginProvider&gt;(),<br>      child: Scaffold(),<br>    );<br>  }<br>}</pre><p>Looks reasonable. But it crashes. Why?</p><p>Because Flutter must evaluate:</p><pre>context.read&lt;LoginProvider&gt;()</pre><p>before it can create:</p><pre>ChangeNotifierProvider.value(...)</pre><p>At that moment the hierarchy is:</p><pre>Route 2<br>└── Screen2</pre><p>There is still no provider above Screen2.</p><p>So Flutter immediately throws:</p><pre>ProviderNotFoundException</pre><p>before the wrapper can even be built.</p><pre>MaterialApp<br>│<br>└── Navigator<br>    │<br>    ├── Route 1<br>    │   │<br>    │   └── Provider<br>    │       │<br>    │       └── Screen1<br>    │<br>    └── Route 2<br>        │<br>        └── Screen2<br>            │<br>            └── Provider.value (no provider above screen2)</pre><h3>Why Wrapping During Navigation Works</h3><p>During navigation:</p><pre>Navigator.push(<br>  context,<br>  MaterialPageRoute(<br>    builder: (_) =&gt; ChangeNotifierProvider.value(<br>      value: context.read&lt;LoginProvider&gt;(),<br>      child: Screen2(),<br>    ),<br>  ),<br>);</pre><p>the old route’s context is still available.</p><p>Specifically:</p><pre>context.read&lt;LoginProvider&gt;()</pre><p>executes inside Screen1’s subtree.</p><p>At that moment:</p><pre>Route 1<br>└── Provider(LoginProvider)<br>    └── Screen1 ← context</pre><p>Provider can be found successfully.</p><p>The instance is retrieved and passed into Route 2.</p><p>Screen2 never has to search for the original provider.</p><p>It receives the provider already attached above it.</p><pre>MaterialApp<br>│<br>└── Navigator<br>    │<br>    ├── Route 1<br>    │   │<br>    │   └── Provider<br>    │       │<br>    │       └── Screen1<br>    │<br>    └── Route 2<br>        │<br>        └── Provider.value (same instance and provider above screen2)<br>            │<br>            └── Screen2</pre><h3>Quick Summary</h3><ul><li>context.read(), context.watch(), and Consumer can only access providers that are <strong>ancestors of the current BuildContext</strong>.</li><li>A BuildContext does not gain access to a provider simply because the provider is returned from the same build() method. The context must belong to a widget that is <strong>below the provider in the widget tree</strong>.</li><li>Builder works because it creates a new BuildContext that is a descendant of the provider.</li><li>Flutter routes create separate widget subtrees. A provider created inside Route 1 is not automatically visible inside Route 2.</li><li>ProviderNotFoundException usually means one of two things:</li><li>The provider is below the current context.</li><li>The provider exists in a different route subtree.</li><li>To share an existing provider instance with a new route, wrap the route during navigation using ChangeNotifierProvider.value().</li><li>ChangeNotifierProvider.value() does <strong>not</strong> create a new provider. It exposes the same existing instance to another subtree.</li><li>Wrapping a screen with .value inside that screen&#39;s build() method won&#39;t work if obtaining the provider itself requires context.read(), because the provider lookup happens before the wrapper is created.</li></ul><p>Once you understand that Provider performs an ancestor lookup starting from the current BuildContext, most ProviderNotFoundException errors become straightforward to diagnose and fix.</p><p>Connect with me:</p><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06ffafa4f864" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you using ‘addPostFrameCallback’ in wrong way?]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/are-you-using-addpostframecallback-in-wrong-way-bc94250202f6?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc94250202f6</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Fri, 29 May 2026 15:33:22 GMT</pubDate>
            <atom:updated>2026-05-29T15:33:22.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i58pZyHeiVWcpHsmslkp_A.png" /></figure><p>Flutter gives developers deep control over the UI rendering lifecycle. One of the most misunderstood yet extremely useful APIs in this lifecycle is:</p><pre>WidgetsBinding.instance.addPostFrameCallback()</pre><p>Many developers use it randomly to “fix” errors without truly understanding what it does. Sometimes it works, but in many cases it creates hidden bugs, rebuild loops, and architectural problems.</p><p>In this article, we’ll understand:</p><ul><li>What addPostFrameCallback actually does</li><li>Why it exists</li><li>The most common real-world use cases</li><li>When NOT to use it</li><li>Common mistakes developers make</li></ul><h3>What is addPostFrameCallback?</h3><p>addPostFrameCallback schedules a function to run <strong>after the current frame has been rendered on the screen</strong>.</p><p>In simple words:</p><blockquote><em>“Execute this code after Flutter finishes building and drawing the UI.”</em></blockquote><p>Syntax:</p><pre>WidgetsBinding.instance.addPostFrameCallback((_) {<br>  // code here<br>});</pre><h3>Understanding Flutter’s Rendering Lifecycle</h3><p>A simplified Flutter frame lifecycle looks like this:</p><ol><li>Widget build</li><li>Layout calculation</li><li>Painting/rendering</li><li>Frame completed</li><li>Post frame callbacks execute</li></ol><p>So when you use:</p><pre>WidgetsBinding.instance.addPostFrameCallback()</pre><p>your code runs only after step 4.</p><p>This is important because some operations require:</p><ul><li>a fully built widget tree</li><li>a valid BuildContext</li><li>completed layout information</li><li>rendered UI elements</li></ul><h3>Why Do We Need It?</h3><p>Some UI operations fail if executed too early.</p><p>For example:</p><ul><li>showing dialogs in initState</li><li>navigating immediately</li><li>reading widget size</li><li>scrolling to list end</li><li>triggering UI-dependent provider updates</li></ul><p>These operations depend on the frame being fully rendered.</p><p>That’s exactly where addPostFrameCallback helps.</p><h3>Correct Use Case #1 — Showing a Dialog After Screen Loads</h3><p>This is probably the most common and correct usage.</p><h3>Wrong Approach</h3><pre>@override<br>void initState() {<br>  super.initState();<br>  showDialog(<br>    context: context,<br>    builder: (_) =&gt; AlertDialog(<br>      title: Text(&quot;Welcome&quot;),<br>    ),<br>  );<br>}</pre><p>Why is this wrong?</p><p>At initState, the widget is initialized but not fully rendered yet. The BuildContext may not be ready for overlay operations like dialogs.</p><p>This can cause:</p><ul><li>exceptions</li><li>unstable behavior</li><li>context-related errors</li></ul><h3>Correct Approach</h3><pre>@override<br>void initState() {<br>  super.initState();<br>  WidgetsBinding.instance.addPostFrameCallback((_) {<br>    showDialog(<br>      context: context,<br>      builder: (_) =&gt; AlertDialog(<br>        title: Text(&quot;Welcome&quot;),<br>      ),<br>    );<br>  });<br>}</pre><p>Now Flutter first renders the screen, then opens the dialog safely.</p><h3>Correct Use Case #2 — Navigation After Initial Rendering</h3><p>Very common in:</p><ul><li>splash screens</li><li>auth checks</li><li>onboarding flows</li></ul><h3>Example</h3><pre>@override<br>void initState() {<br>  super.initState();<br>  WidgetsBinding.instance.addPostFrameCallback((_) {<br>    Navigator.pushReplacement(<br>      context,<br>      MaterialPageRoute(<br>        builder: (_) =&gt; HomeScreen(),<br>      ),<br>    );<br>  });<br>}</pre><h3>Why Use It Here?</h3><p>Direct navigation during initialization can sometimes interfere with the current widget build cycle.</p><p>Using addPostFrameCallback ensures:</p><ul><li>the current screen renders properly first</li><li>navigation occurs safely afterward</li></ul><h3>Correct Use Case #3 — Auto Scrolling to Bottom in Chat Apps</h3><p>Imagine a chat application where you want to automatically scroll to the latest message.</p><h3>Problem</h3><p>If you scroll immediately after adding data, the list may not yet be rendered.</p><p>So this may fail:</p><pre>_scrollController.jumpTo(<br>  _scrollController.position.maxScrollExtent,<br>);</pre><p>because the max scroll extent is not calculated yet.</p><h3>Correct Solution</h3><pre>WidgetsBinding.instance.addPostFrameCallback((_) {<br>  _scrollController.jumpTo(<br>    _scrollController.position.maxScrollExtent,<br>  );<br>});</pre><p>Now scrolling happens after the list finishes rendering.</p><h3>Correct Use Case #4 — Reading Widget Size</h3><p>Sometimes you need actual widget dimensions.</p><p>Example:</p><ul><li>custom animations</li><li>overlay positioning</li><li>dynamic UI calculations</li></ul><p>But widget size is unavailable during build.</p><h3>Example</h3><pre>final GlobalKey containerKey = GlobalKey();<br>WidgetsBinding.instance.addPostFrameCallback((_) {<br>  final context = containerKey.currentContext;<br>  final size = context?.size;<br>  print(size);<br>});</pre><h3>Why It Works</h3><p>Widget size becomes available only after:</p><ul><li>layout</li><li>rendering</li></ul><p>addPostFrameCallback waits for that process to complete.</p><h3>When You SHOULD NOT Use addPostFrameCallback</h3><p>Now comes the most important part.</p><p>Many developers overuse this API.</p><p>Just because it fixes something does not mean it is the correct solution.</p><h3>Wrong Usage #1 — Inside build()</h3><p>This is one of the biggest mistakes.</p><h3>Bad Example</h3><pre>@override<br>Widget build(BuildContext context) {<br>  WidgetsBinding.instance.addPostFrameCallback((_) {<br>    print(&quot;called&quot;);<br>  });<br>  return Container();<br>}</pre><h3>Why Is This Dangerous?</h3><p>Because build() can execute many times.</p><p>Every rebuild schedules a new callback.</p><p>This causes:</p><ul><li>repeated executions</li><li>performance issues</li><li>duplicated side effects</li><li>memory overhead</li></ul><h3>Even Worse Example</h3><pre>WidgetsBinding.instance.addPostFrameCallback((_) {<br>  setState(() {});<br>});</pre><p>inside build() creates:</p><pre>build → callback → setState → build → callback → infinite loop</pre><p>This can completely destroy app performance.</p><h3>Wrong Usage #2 — For Normal Business Logic</h3><p>Some developers use it for regular API calls.</p><h3>Bad Example</h3><pre>WidgetsBinding.instance.addPostFrameCallback((_) {<br>  fetchUsers();<br>});</pre><p>But fetching users has nothing to do with frame rendering.</p><h3>Better Approach</h3><pre>@override<br>void initState() {<br>  super.initState();<br>  fetchUsers();<br>}</pre><p>Use addPostFrameCallback only when the logic depends on rendered UI.</p><h3>Wrong Usage #3 — Hiding Architecture Problems</h3><p>Developers often use it to silence errors like:</p><pre>setState() or markNeedsBuild() called during build</pre><p>Instead of fixing the actual problem.</p><h3>Common Example</h3><pre>WidgetsBinding.instance.addPostFrameCallback((_) {<br>  provider.loadData();<br>});</pre><p>without understanding why rebuild timing is wrong.</p><p>Sometimes the real issue is:</p><ul><li>incorrect state management</li><li>triggering UI updates during build</li><li>poor widget structure</li></ul><p>Using addPostFrameCallback blindly only hides symptoms temporarily.</p><h3>addPostFrameCallback vs Future.delayed(Duration.zero)</h3><p>Many developers confuse these.</p><h3>Future.delayed(Duration.zero)</h3><pre>Future.delayed(Duration.zero, () {});</pre><p>This schedules execution later in the event loop.</p><p>But:</p><ul><li>it is NOT tied to rendering</li><li>not guaranteed after frame completion</li></ul><h3>addPostFrameCallback</h3><pre>WidgetsBinding.instance.addPostFrameCallback((_) {});</pre><p>This is specifically connected to Flutter’s rendering pipeline.</p><p>It guarantees:</p><ul><li>frame completed</li><li>layout finished</li><li>UI rendered</li></ul><p>For UI-dependent logic, this is the safer option.</p><h3>Best Practices</h3><h3>Use it mainly for UI side effects</h3><p>Examples:</p><ul><li>dialogs</li><li>snackbars</li><li>navigation</li><li>scrolling</li><li>focus requests</li><li>reading widget size/position</li></ul><h3>Prefer placing it in initState</h3><p>Most safe usages look like this:</p><pre>@override<br>void initState() {<br>  super.initState();<br>  WidgetsBinding.instance.addPostFrameCallback((_) {<br>    // UI side effect<br>  });<br>}</pre><h3>Keep callbacks lightweight</h3><p>Avoid heavy computation inside callbacks.</p><p>They execute on the UI thread.</p><h3>Final Thoughts</h3><p>addPostFrameCallback is not a hack.</p><p>It is a lifecycle-aware scheduling tool designed for operations that depend on completed UI rendering.</p><p>Used correctly, it solves many legitimate Flutter problems elegantly.</p><p>Used incorrectly, it creates:</p><ul><li>hidden bugs</li><li>rebuild loops</li><li>unnecessary complexity</li><li>performance issues</li></ul><p>The key rule is simple:</p><blockquote><em>Use it only when your code genuinely depends on the UI frame being fully rendered.</em></blockquote><p>If the operation does not require rendered UI, you probably do not need addPostFrameCallback.</p><h3>Quick Summary</h3><h3>Good Uses</h3><ul><li>Dialogs</li><li>Navigation after render</li><li>Auto-scrolling</li><li>Widget size measurement</li><li>Snackbar</li><li>Focus handling</li></ul><h3>Bad Uses</h3><ul><li>Inside build()</li><li>Regular API calls</li><li>Infinite setState patterns</li><li>Hiding architecture problems</li><li>General async scheduling</li></ul><h3>One-Line Mental Model</h3><blockquote><em>“Run this code after Flutter finishes drawing the current screen.”</em></blockquote><p>Connect with me:</p><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc94250202f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Have you heard about Fixtures in Flutter ?]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/have-you-heard-about-fixtures-in-flutter-03eaadd70ff8?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/03eaadd70ff8</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 17:18:38 GMT</pubDate>
            <atom:updated>2026-04-28T17:18:38.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGofy1Xid9kbVT-fh4basQ.png" /></figure><p>When Flutter apps grow beyond simple demos, testing stops being optional. You start dealing with APIs, complex JSON responses, and evolving backend contracts. At that point, one subtle but powerful technique can drastically improve your test quality: fixtures.</p><p>This article walks through what fixtures are, why they matter, and how to use them effectively in a real Flutter codebase.</p><h3>What Are Fixtures?</h3><p>A fixture is simply a static file containing sample data used in tests. In Flutter projects, fixtures are most commonly JSON files that mimic real API responses.</p><p>Instead of hardcoding large maps inside your test files, you store them separately and load them during test execution.</p><p>Think of fixtures as:</p><p>“Snapshots of real-world data your app expects.”</p><h3>Why Fixtures Matter</h3><p>As your app interacts with APIs, JSON structures tend to grow:</p><p>- Nested objects<br>- Optional fields<br>- Lists of items<br>- Changing backend contracts</p><p>Hardcoding such data directly inside tests leads to messy, unreadable, and fragile test files.</p><p>Fixtures solve several real-world problems:</p><h4>1. Readability</h4><p>Compare this:</p><pre>final json = {<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john.doe@test.com&quot;,<br>  &quot;address&quot;: {<br>    &quot;city&quot;: &quot;Mumbai&quot;,<br>    &quot;pincode&quot;: &quot;400001&quot;<br>  }<br>};</pre><p>With this:</p><pre>final jsonString = readFixture(&#39;user.json&#39;);<br>final json = jsonDecode(jsonString);</pre><p>The second approach is cleaner and easier to maintain.</p><h4>2. Realistic Testing</h4><p>Fixtures usually come from:</p><p>- Actual API responses<br>- Postman exports<br>- Backend team samples</p><p>This ensures your tests reflect real-world scenarios, not simplified assumptions.</p><h4>3. Maintainability</h4><p>When API responses change:</p><p>- Update one JSON file<br>- All related tests automatically use the updated structure</p><p>Without fixtures, you&#39;d have to update JSON in multiple test files.</p><h4><strong>4. Separation of Concerns</strong></h4><p>Tests should focus on behavior, not bulky data setup.</p><p>Fixtures move data out of test logic, keeping tests:</p><p>- Focused<br>- Minimal<br>- Intent-driven</p><h3>Where Fixtures Are Used</h3><p>Fixtures are most commonly used in:</p><h4>Model Testing</h4><p>Validating JSON parsing &quot;fromJson&quot; and serialization &quot;toJson&quot;</p><h4>Repository Testing</h4><p>Simulating API responses without making real network calls</p><h4>Data Source Testing</h4><p>Mocking backend responses in remote/local data sources</p><h3>A Practical Example</h3><p>API Response (Fixture)</p><p>Create a file: test/fixtures/user.json</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john.doe@test.com&quot;,<br>  &quot;address&quot;: {<br>    &quot;city&quot;: &quot;Mumbai&quot;,<br>    &quot;pincode&quot;: &quot;400001&quot;<br>  }<br>}</pre><h4><strong>Model</strong></h4><pre>class Address {<br>  final String city;<br>  final String pincode;<br>  Address({required this.city, required this.pincode});<br>  factory Address.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return Address(<br>      city: json[&#39;city&#39;],<br>      pincode: json[&#39;pincode&#39;],<br>    );<br>  }<br>  Map&lt;String, dynamic&gt; toJson() =&gt; {<br>        &#39;city&#39;: city,<br>        &#39;pincode&#39;: pincode,<br>      };<br>}</pre><pre>class User {<br>  final int id;<br>  final String name;<br>  final String email;<br>  final Address address;<br>  User({<br>    required this.id,<br>    required this.name,<br>    required this.email,<br>    required this.address,<br>  });<br>  factory User.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return User(<br>      id: json[&#39;id&#39;],<br>      name: json[&#39;name&#39;],<br>      email: json[&#39;email&#39;],<br>      address: Address.fromJson(json[&#39;address&#39;]),<br>    );<br>  }<br>  Map&lt;String, dynamic&gt; toJson() =&gt; {<br>        &#39;id&#39;: id,<br>        &#39;name&#39;: name,<br>        &#39;email&#39;: email,<br>        &#39;address&#39;: address.toJson(),<br>      };<br>}</pre><h4><strong>Fixture Reader Utility</strong></h4><p>Create a helper:</p><p>test/helpers/fixture_reader.dart</p><pre>import &#39;dart:io&#39;;<br><br>String readFixture(String name) {<br>  return File(&#39;test/fixtures/$name&#39;).readAsStringSync();<br>}</pre><h3>Unit Test</h3><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:your_app/models/user.dart&#39;;<br>import &#39;../helpers/fixture_reader.dart&#39;;<br>void main() {<br>  group(&#39;User Model&#39;, () {<br>    late Map&lt;String, dynamic&gt; jsonMap;<br><br>    setUp(() {<br>      final jsonString = readFixture(&#39;user.json&#39;);<br>      jsonMap = jsonDecode(jsonString);<br>    });<br><br>    test(&#39;should parse JSON correctly&#39;, () {<br>      final result = User.fromJson(jsonMap);<br>      expect(result.id, 1);<br>      expect(result.name, &#39;John Doe&#39;);<br>      expect(result.address.city, &#39;Mumbai&#39;);<br>    });<br><br>    test(&#39;should convert model back to JSON&#39;, () {<br>      final model = User.fromJson(jsonMap);<br>      final result = model.toJson();<br>      expect(result, jsonMap);<br>    });<br>  });<br></pre><h3>Recommended Folder Structure</h3><p>A clean and scalable structure looks like this:</p><pre>test/<br> ├── fixtures/<br> │    ├── user.json<br> │    ├── user_list.json<br> │    └── error_response.json<br> │<br> ├── helpers/<br> │    └── fixture_reader.dart<br> │<br> ├── models/<br> │    └── user_test.dart<br> │<br> ├── data_sources/<br> │    └── user_remote_data_source_test.dart<br> │<br> └── repositories/<br>      └── user_repository_test.dart</pre><p>This structure keeps:</p><p>- Data (fixtures)<br>- Utilities<br>- Tests</p><p>well-organized and easy to navigate.</p><h3>Going Beyond Basic Fixtures</h3><p>As your app grows, you can level up your fixture usage:</p><h4><strong>Multiple Scenarios</strong></h4><p>Create different fixtures for different cases:</p><pre>test/<br> ├── fixtures/<br> │    ├── user_valid.json<br> │    ├── user_empty.json<br> │    └── user_missing_fields.json</pre><p>This helps test edge cases without complicating test code.</p><h4><strong>Error Simulation</strong></h4><p>You can simulate backend failures:</p><pre>{<br>  &quot;error&quot;: &quot;User not found&quot;<br>}</pre><p>Useful for testing error handling in repositories and data sources.</p><h4>Lists and Pagination</h4><pre>[<br>  { &quot;id&quot;: 1, &quot;name&quot;: &quot;A&quot; },<br>  { &quot;id&quot;: 2, &quot;name&quot;: &quot;B&quot; }<br>]<br><br>Or paginated responses:<br><br>{<br>  &quot;page&quot;: 1,<br>  &quot;data&quot;: [ ... ]<br>}</pre><h3><strong>Common Mistakes to Avoid</strong></h3><p>- Copy-pasting JSON inside test files instead of using fixtures<br>- Using overly simplified JSON that doesn’t match real API responses<br>- Not testing invalid or edge-case fixtures<br>- Keeping fixtures unorganized or scattered</p><h3>When Not to Use Fixtures</h3><p>Fixtures are powerful, but not always necessary.</p><p>Avoid them when:</p><ul><li>Testing simple models with 2–3 fields</li><li>Writing very small, isolated unit tests</li><li>Data is trivial and unlikely to change</li></ul><h3><em>Final Thoughts</em></h3><p>Fixtures might seem like a small testing detail, but they bring a significant shift in how you approach testing:</p><p>- Tests become cleaner<br>- Data becomes reusable<br>- Scenarios become realistic<br>- Maintenance becomes easier</p><p>If you’re preparing for interviews or working on production apps, adopting fixture-based testing is a strong signal of writing mature, scalable test code.</p><p>Once you start using fixtures consistently, going back to hardcoded JSON will feel like a step backward.</p><p>Connect with me:</p><p>https://www.linkedin.com/in/suraj-suryawanshi-921901211/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03eaadd70ff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding All Types of Classes in Flutter.]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/understanding-all-types-of-classes-in-flutter-f7efa3dc32ea?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7efa3dc32ea</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 18:07:52 GMT</pubDate>
            <atom:updated>2026-03-27T18:42:02.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAu937KkbsKY66HsIQ0eeQ.png" /></figure><p>When working with Flutter, understanding Dart’s class modifiers is essential for writing clean, maintainable, and scalable code. These modifiers help you control how classes are used, extended, or restricted — which becomes especially important in large applications.</p><p>In this blog, we’ll break down all important types of classes in Dart (used in Flutter), with simple examples and real-world use cases.</p><h3>1. Normal Class</h3><p>This is the default class you use in Dart.</p><h3>Example:</h3><pre>class User {<br>  String name;<br>  User(this.name);<br>}</pre><h3>Use Case:</h3><ul><li>Models (User, Product)</li><li>Entities</li><li>Widgets</li></ul><p>Use this when you don’t need any restrictions.</p><h3>2. Base Class</h3><p>A base class can be extended or implemented in same library</p><p>can be extended but can’t be implemented outside library.</p><p>You must mark any class that implements or extends a base class as base, final, or sealed. This prevents outside libraries from breaking the base class guarantees.</p><h3>Example:</h3><pre>a.dart<br><br>base class UseCase{}<br><br>base class GetUserUseCase extends UseCase{}<br><br>base class GetUserUseCase implements UseCase{}</pre><pre>import &#39;a.dart&#39;<br><br>base class GetUserUseCase extends UseCase{}<br><br>base class GetUserUseCase implements UseCase{}  //Invalid</pre><h3>Use Case:</h3><ul><li>When you want controlled inheritance</li><li>Prevent misuse via implements</li><li>can’t ignore original implementation</li></ul><p>Useful in framework-level design.</p><h3>3. Interface Class</h3><p>An interface class can be extended or implemented in same library,</p><p>can be implemented but can’t be extended outside library.</p><h3>Example:</h3><pre>a.dart<br><br>interface class Logger {<br>  void log(String message);<br>}<br><br>class FileLogger implements Logger {<br>  @override<br>  void log(String message) {<br>    print(&quot;Log: $message&quot;);<br>  }<br>}<br><br>class FileLogger extends Logger{<br>  @override<br>  void log(String message) {<br>    print(&quot;Log: $message&quot;);<br>  }<br>}</pre><pre>import &#39;a.dart&#39;<br><br>class FileLogger implements Logger {<br>  @override<br>  void log(String message) {<br>    print(&quot;Log: $message&quot;);<br>  }<br>}<br><br>class FileLogger extends Logger{}    //Invalid</pre><h3>Use Case:</h3><ul><li>Define contracts without sharing implementation</li><li>Useful for dependency injection</li></ul><h3>4. Abstract Class</h3><p>An abstract class acts as a <strong>blueprint</strong>. It cannot be instantiated and may contain abstract methods (methods without implementation).</p><p>It provides featurs of both interface+ base classs as it can be both extended and implemented by child class.</p><h3>Example:</h3><pre>a.dart<br><br>abstract class UserRepository{<br>  Future&lt;String&gt; getUser();<br>  Future&lt;String&gt; log(){}<br>}<br><br>class UserRepositoryImpl extends UserRepository {<br>  @override<br>  Future&lt;String&gt; getUser() {<br>    print(&quot;extended inside library&quot;);<br>  }<br>}<br><br>class UserRepositoryImpl implements UserRepository {<br>  @override<br>  Future&lt;String&gt; getUser() {<br>    print(&quot;implemented inside library&quot;);<br>  }<br>  Future&lt;String&gt; log(){<br>     print(&#39;implemented inside library&#39;);<br>  }<br>}</pre><pre>import &#39;a.dart&#39;<br><br>class UserRepositoryImpl extends UserRepository {<br>  @override<br>  Future&lt;String&gt; getUser() {<br>    print(&quot;extended outside library&quot;);<br>  }<br>}<br><br>class UserRepositoryImpl implements UserRepository {<br>  @override<br>  Future&lt;String&gt; getUser() {<br>    print(&quot;implemented outside library&quot;);<br>  }<br>  Future&lt;String&gt; log(){<br>     print(&#39;implemented outside library&#39;);<br>  }<br>}</pre><h3>Use Case in Flutter:</h3><ul><li>Repository pattern</li><li>Clean architecture</li></ul><p>Helps in writing testable and loosely coupled code.</p><h3>5. Final Class</h3><p>A final class cannot be extended, implemented, or mixed in outside its library.</p><h3>Example:</h3><pre>final class PaymentService {<br>  void processPayment() {<br>    print(&quot;Processing payment&quot;);<br>  }<br>}<br><br>class CouponService extends PaymentService{}   //Invalid</pre><h3>Use Case:</h3><ul><li>When you want to <strong>lock a class completely</strong></li><li>Prevent modification of business logic</li></ul><p>Common in:</p><ul><li>API services</li><li>Utility classes</li><li>Model classes</li><li>App Constants</li><li>State Objects for Bloc/Provider</li></ul><h3>6. Sealed Class</h3><p>A sealed class restricts inheritance to the <strong>same file only</strong>.</p><h3>Example:</h3><pre>sealed class AuthState {}<br><br>final class LoggedIn extends AuthState {}<br><br>final class LoggedOut extends AuthState {}</pre><h3>Use Case in Flutter:</h3><ul><li>State management (Bloc, Riverpod)</li><li>UI states</li></ul><pre>switch (state) {<br>  case LoggedIn():<br>    print(&quot;User logged in&quot;);<br>  case LoggedOut():<br>    print(&quot;User logged out&quot;);<br>}</pre><p>Benefits:</p><ul><li>Compile-time safety</li><li>No need for default cases</li><li>Prevents unexpected subclasses</li><li>exhaustive checking in switch</li></ul><h3>7. Mixin Class</h3><p>A mixin allows code reuse without inheritance.</p><h3>Example:</h3><pre>mixin ValidatorMixin {<br>  String? validateEmail(String value) {<br>    if (value.isEmpty) return &quot;Email required&quot;;<br>    if (!value.contains(&quot;@&quot;)) return &quot;Invalid email&quot;;<br>    return null;<br>  }<br><br>  String? validatePassword(String value) {<br>    if (value.length &lt; 6) return &quot;Password too short&quot;;<br>    return null;<br>  }<br>}</pre><pre>class LoginScreen extends StatelessWidget with ValidatorMixin {<br>  final emailController = TextEditingController();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return TextFormField(<br>      controller: emailController,<br>      validator: (value) =&gt; validateEmail(value ?? &quot;&quot;),<br>    );<br>  }<br>}<br></pre><h3>Use Case in Flutter:</h3><ul><li>Reusable UI logic</li><li>Animation controllers</li><li>Form validation</li></ul><p>Mixins are heavily used inside Flutter itself.</p><h3>8. Enum (Special Type)</h3><p>While not exactly a class, enums are widely used.</p><h3>Example:</h3><pre>enum Status { loading, success, error }</pre><p>or with values</p><pre>enum Vehical { <br>  car(tyres:4),<br>  bike(tyres:2);<br><br>  const Vehical({required this.tyres});<br><br>  final int tyres;<br><br>}</pre><h3>Use Case:</h3><ul><li>API states</li><li>UI states</li><li>Finite sets of values</li></ul><h3>Quick Comparison Table</h3><pre><br>Type            Can Extend        Can Implement       Purpose<br>class              Yes               Yes              Default<br>abstract           Yes               Yes              Blueprint<br>final              Yes               No               Lock class<br>sealed             Yes(same file)    No               Controlled states<br>base               Yes               No               Controlled inheritance<br>interface          No                No               Contract<br>mixin              No                No               Code reuse</pre><h3>When to Use What (Practical Guide)</h3><ul><li>Use <strong>abstract class</strong> → when defining architecture (e.g., repositories)</li><li>Use <strong>sealed class</strong> → for state management (very common in Flutter apps)</li><li>Use <strong>final class</strong> → when you want strict control and no modification</li><li>Use <strong>base class</strong> → when you want inheritance but controlled usage</li><li>Use <strong>interface class</strong> → when defining contracts (like APIs)</li><li>Use <strong>mixin</strong> → for reusable logic across multiple classes</li></ul><p>If used correctly:</p><ul><li>Your code becomes safer</li><li>Easier to maintain</li><li>More predictable in large teams</li></ul><p>A good Flutter developer doesn’t just write code — they design it thoughtfully using the right abstractions.</p><h3>Final Thoughts</h3><p>Understanding these class types is not just about syntax — it’s about writing <strong>robust and scalable Flutter applications</strong>.</p><p><strong><em>I understand some of you still will be confused specially between abstract interface and base classes specially because they can be used interchangeably. I will try to explain the exact difference between then in upcoming blog so stay tuned.</em></strong></p><h3>Connect with me</h3><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7efa3dc32ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The new switch expression in Dart will make your life easy.]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/the-new-switch-expression-in-dart-will-make-your-life-easy-697bc3df5973?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/697bc3df5973</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[switch]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 18:17:03 GMT</pubDate>
            <atom:updated>2026-02-08T18:17:03.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaMpSabhbfKj5Aj-s4JoqQ.jpeg" /></figure><p>I am assuming that probably some of you have already started using the new switch expression introduced Dart 3. But still this article will make you to switch to new switch expression if you have not yet.</p><p>Dart 3 introduced a <strong>completely revamped </strong><strong>switch</strong> based on <strong>pattern matching</strong>.</p><p>This is one of the biggest language upgrades in Dart’s history and directly impacts how clean, safe, and expressive your Flutter/Dart code can be.</p><h3>1. Old switch in Dart (Pre–Dart 3)</h3><h4>Syntax (Statement-only)</h4><pre>switch (day) {<br>  case 1:<br>    print(&#39;Monday&#39;);<br>    break;<br>  case 2:<br>    print(&#39;Tuesday&#39;);<br>    break;<br>  default:<br>    print(&#39;Unknown day&#39;);<br>}</pre><h4>Key Characteristics</h4><ul><li><strong>Only statements</strong>, not expressions</li><li>Required break (easy to forget)</li><li>Works only with :int, String, enum</li><li>No de-structuring</li><li>No conditions inside cases</li><li>No compile-time exhaustiveness checking</li></ul><h3>2. New switch in Dart 3 (Pattern Matching)</h3><p>Dart 3 introduces <strong>switch expressions + pattern matching</strong>.</p><h4>Example: Switch as an Expression</h4><pre>String dayName = switch (day) {<br>  1 =&gt; &#39;Monday&#39;,<br>  2 =&gt; &#39;Tuesday&#39;,<br>  _ =&gt; &#39;Unknown&#39;,<br>};</pre><h4>Why this is huge:</h4><ul><li>No break</li><li>Returns a value</li><li>Cleaner &amp; safer</li><li>Exhaustiveness checking</li></ul><h3>3. Pattern Matching: The Real Power</h3><h4>a) Constant Patterns (Old behaviour + better syntax)</h4><pre>final result = switch (status) {<br>  &#39;success&#39; =&gt; &#39;Done&#39;,<br>  &#39;error&#39; =&gt; &#39;Failed&#39;,<br>   _ =&gt; &#39;Pending&#39;,<br>};</pre><h4>b) Relational Patterns (NEW)</h4><p>You can now match <strong>conditions directly</strong>:</p><pre>String grade = switch (marks) {<br>  &gt;= 90 =&gt; &#39;A&#39;,<br>  &gt;= 75 =&gt; &#39;B&#39;,<br>  &gt;= 60 =&gt; &#39;C&#39;,<br>  _ =&gt; &#39;Fail&#39;,<br>};</pre><ul><li>Previously =&gt; required if-else</li><li>Now =&gt; readable &amp; declarative</li></ul><h4>c) Logical OR (||) and AND (&amp;&amp;) Patterns</h4><pre>String trafficLight = switch (color) {<br>  &#39;red&#39; || &#39;yellow&#39; =&gt; &#39;Stop&#39;,<br>  &#39;green&#39; =&gt; &#39;Go&#39;,<br>  _ =&gt; &#39;Invalid&#39;,<br>};</pre><h4>d) Type Patterns</h4><pre>String describe(Object value) =&gt; switch (value) {<br>  int i =&gt; &#39;Integer: $i&#39;,<br>  double d =&gt; &#39;Double: $d&#39;,<br>  String s =&gt; &#39;String: $s&#39;,<br>  _ =&gt; &#39;Unknown type&#39;,<br>};</pre><p>Cleaner than is + casting</p><h3>4. De-structuring Objects &amp; Records</h3><h4>Record Matching</h4><pre>(String, int) user = (&#39;Suraj&#39;, 26);</pre><pre>final message = switch (user) {<br>  (String name, int age) =&gt; &#39;Name: $name, Age: $age&#39;,<br>};</pre><h4>Class De-structuring</h4><pre>class User {<br>  final String name;<br>  final int age;<br>  User(this.name, this.age);<br>}</pre><pre>String info = switch (user) {<br>  User(name: &#39;Suraj&#39;, age: var a) =&gt; &#39;Suraj is $a years old&#39;,<br>  User(name: var name, age: var age) =&gt; &#39;$name ($age)&#39;,<br>};</pre><p>Previously impossible with switch</p><h3>5. Switch Statements (Still Supported)</h3><p>You can still use <strong>statement-style switch</strong>, but now enhanced:</p><pre>switch (value) {<br>  case &gt; 100:<br>    print(&#39;Large&#39;);<br>  case &lt;= 100 &amp;&amp; &gt; 50:<br>    print(&#39;Medium&#39;);<br>  default:<br>    print(&#39;Small&#39;);<br>}</pre><h3>6. Exhaustiveness Checking (Compiler Safety)</h3><h4>Enums Example</h4><pre>enum Status { loading, success, error }</pre><pre>String text = switch (status) {<br>  Status.loading =&gt; &#39;Loading...&#39;,<br>  Status.success =&gt; &#39;Success!&#39;,<br>  Status.error =&gt; &#39;Error!&#39;,<br>};</pre><ul><li>if you miss a case → <strong>compile-time error</strong></li><li>No more hidden runtime bugs</li></ul><h3>7. Old vs New Switch — Comparison Table</h3><pre>| Feature                   | Old Switch     | Dart 3 Switch    |<br>| --------------------------| ---------------| -----------------|<br>| Expression support        |    NO          |     YES          |<br>| Break required            |    YES         |     NO           |<br>| Pattern matching          |    NO          |     YES          |<br>| Type matching             |    NO          |     YES          |<br>| Destructuring             |    NO          |     YES          |<br>| Conditions (`&gt;`, `&lt;`)     |    NO          |     YES          |<br>| Exhaustiveness check      |    NO          |     YES          |<br>| Null safety friendly      |    PARTIAL     |     YES          |</pre><h3>8. Real Flutter Use Case</h3><h3>Handling API State</h3><pre>Widget buildUI(ApiState state) {<br>  return switch (state) {<br>    Loading() =&gt; const CircularProgressIndicator(),<br>    Success(data: var list) =&gt; ListView.builder(<br>        itemCount: list.length,<br>        itemBuilder: (_, i) =&gt; Text(list[i]),<br>      ),<br>    Error(message: var msg) =&gt; Text(msg),<br>  };<br>}</pre><p>This replaces:</p><ul><li>if-else</li><li>is checks</li><li>manual casting</li><li>boilerplate</li></ul><h3>9. Summary</h3><h3>Why Dart 3 Switch Is a Big Deal</h3><ul><li><strong>Declarative</strong> (what you want, not how)</li><li><strong>Less boilerplate</strong></li><li><strong>Safer</strong> (compile-time checks)</li><li><strong>More readable</strong></li><li><strong>Perfect for Flutter UI &amp; state handling</strong></li><li><strong>Scales beautifully for large apps</strong></li></ul><h3>10. When Should YOU Use It?</h3><p>Use <strong>new switch</strong> when:</p><ul><li>Mapping values → UI / text</li><li>Handling states</li><li>Working with enums, sealed classes</li><li>Parsing API responses</li><li>Writing clean Flutter widgets</li></ul><p>Avoid when:</p><ul><li>You need complex imperative logic inside cases</li></ul><h3>Final Thoughts</h3><p>In this article we have covered the basic difference between old style and new switch case. With this you can start using the new switch case in your flutter projects. In next article we will decode and deep dive into some fundamental concepts of switch case. so stay tuned.</p><p>If you enjoyed this:</p><ul><li>Clap</li><li>Share</li><li>Follow for more beginner-friendly tech blogs</li></ul><h3>Connect with me</h3><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=697bc3df5973" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ever Felt: “I Didn’t Know This Thing Worked This Way”]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/ever-felt-i-didnt-know-this-thing-worked-this-way-62cd6f2bc490?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/62cd6f2bc490</guid>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[convention]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 18:11:41 GMT</pubDate>
            <atom:updated>2026-02-01T18:42:26.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXHt0ZQWThdZQyDLTgI0nA.png" /></figure><p>If you’ve ever used a modern framework and thought:</p><blockquote><em>“</em>Wait… why does this work without any setup<em>?”</em></blockquote><p>or after lot of debugging</p><blockquote>“I didn’t know this was the correct way to do it”</blockquote><p>You’ve already experienced <strong>Convention over Configuration</strong> — even if you didn’t know its name.</p><p>In this article, we’ll understand:</p><ul><li>What Convention over Configuration really means</li><li>Why modern frameworks use it</li><li>A simple Spring Boot example</li><li>A simple Flutter example</li><li>Why you <em>don’t</em> usually implement it yourself</li></ul><p>No theory overload. Just clarity.</p><h3>What Is Convention Over Configuration?</h3><blockquote><strong><em>Convention over Configuration means:</em></strong><em><br> </em>If you follow predefined rules (conventions), you don’t need to write extra configuration.</blockquote><p>Instead of telling the framework <strong>everything explicitly</strong>, the framework assumes <strong>sensible defaults</strong>.</p><p>You focus on <strong>business logic</strong>, not setup.</p><h3>A Simple Analogy</h3><p>Imagine driving a car.</p><p>You don’t configure:</p><ul><li>Which pedal is the brake</li><li>Which side the steering wheel is on</li><li>What red traffic light means</li></ul><p>Because there are <strong>conventions</strong>:</p><ul><li>Red → Stop</li><li>Green → Go</li><li>Right pedal → Accelerator</li></ul><p>If every driver had to configure this manually, driving would be chaos.</p><p>Frameworks work the same way.</p><h3>The Problem CoC Solves</h3><p>Before CoC, applications were:</p><ul><li>Full of configuration files</li><li>Verbose and repetitive</li><li>Hard to maintain</li><li>Easy to misconfigure</li></ul><p>Developers spent more time <strong>wiring things together</strong> than solving real problems.</p><h3>Spring Boot Example</h3><p>Let’s see Convention over Configuration in action.</p><h3>Step 1: Create a Controller</h3><pre>@RestController<br>public class HelloController {<br>    @GetMapping(&quot;/hello&quot;)<br>    public String hello() {<br>        return &quot;Hello World&quot;;<br>    }<br>}</pre><p>That’s it.</p><p>No XML.<br> No routing config.<br> No server setup.</p><h3>What You Didn’t Configure (But Still Works)</h3><p>Spring Boot automatically:</p><ul><li>Detects this class as a controller</li><li>Maps /hello to the method</li><li>Starts an embedded server</li><li>Handles HTTP requests &amp; responses</li></ul><p>Why?</p><p>Because you followed <strong>conventions</strong>:</p><ul><li>Class is inside the base package</li><li>Annotated with @RestController</li><li>Uses @GetMapping</li></ul><p><strong>Spring Boot assumes everything else.</strong></p><h3>How It Worked Behind the Scenes</h3><p>Spring Boot follows rules like:</p><ul><li>Scan classes from the main application package</li><li>Treat @RestController as a web endpoint</li><li>Auto-configure web server if web dependency exists</li></ul><p>You didn’t write configuration — <br> you <strong>followed conventions</strong>.</p><h3>Without Convention (Old-Style Configuration)</h3><p>Before CoC, you had to do this:</p><pre>&lt;bean class=&quot;com.app.HelloController&quot;/&gt;<br>&lt;servlet-mapping&gt;<br>    &lt;url-pattern&gt;/hello&lt;/url-pattern&gt;<br>&lt;/servlet-mapping&gt;</pre><p>Now imagine doing this for <strong>every controller</strong></p><p>That’s what CoC saved us from.</p><h3>Flutter Example: pubspec.yaml Asset &amp; Font Loading</h3><h4>The Convention</h4><blockquote><em>Declare assets and fonts in </em><em>pubspec.yaml<br> → Flutter loads them automatically.</em></blockquote><pre>flutter:<br>  assets:<br>    - assets/images/</pre><p>Usage</p><pre>Image.asset(&#39;assets/images/logo.png&#39;);  //Works<br>Image.asset(&#39;images/logo.png&#39;);         //Works<br>Image.asset(&#39;logo.png&#39;);                //This will not work</pre><p>This tells Flutter:</p><blockquote><em>“Include everything inside </em><em>assets/images/ as assets.<br> The full path you reference in </em><em>Image.asset() </em><strong><em>must include </em></strong><strong><em>assets/images/ or images/</em></strong><em>”</em></blockquote><p>So Flutter <strong>does NOT automatically search your project root</strong>.</p><p>If you want to customize — you <em>can</em> — but you’re not forced to.</p><h3>Important Clarification</h3><h3>Do developers “implement” Convention over Configuration?</h3><p>No — usually not.</p><p>Framework creators implement CoC.<br> Application developers <strong>understand and follow it</strong>.</p><p>Your job is to:</p><ul><li>Respect conventions</li><li>Avoid unnecessary configuration</li><li>Customize only when required</li></ul><h3>Why CoC Is So Powerful</h3><h3>Benefits</h3><ul><li>Less boilerplate</li><li>Faster development</li><li>Cleaner code</li><li>Easier onboarding</li><li>Fewer bugs</li></ul><h3>But CoC Is Not Magic</h3><p>There are trade-offs:</p><ul><li>Some behaviour is implicit</li><li>Debugging requires understanding conventions</li><li>Breaking conventions can cause confusion</li></ul><p>That’s why good frameworks follow:</p><blockquote><strong><em>“Conventions by default, configuration when needed.”</em></strong></blockquote><h3>Why This Concept Is Framework-Agnostic</h3><p>You’ll find CoC in:</p><ul><li>Spring Boot</li><li>Flutter</li><li>Django</li><li>Rails</li><li>React</li><li>Next.js</li></ul><p>Frameworks change.<br> <strong>Conventions remain.</strong></p><h3>Pro Tip</h3><p>If you’re <strong>struggling with a framework</strong><br> — or planning to start working with a new one —</p><p><strong>Spend some time understanding its conventions first.</strong></p><p>Not APIs.<br> Not advanced features.<br> Just the <strong>basic rules the framework assumes</strong>.</p><p>Because later:</p><ul><li>You’ll get <strong>fewer surprises</strong></li><li>You’ll feel <strong>less confused</strong></li><li>You’ll spend <strong>less time debugging “why is this happening?”</strong></li><li>And you’ll stop blaming the framework for things <em>you unknowingly broke</em></li></ul><p>Most “framework bugs” are actually:</p><blockquote>“I didn’t know this was the convention.”</blockquote><p>Understand the conventions early, and suddenly:</p><ul><li>Code feels predictable</li><li>Docs make sense</li><li>Debugging becomes easier</li></ul><p>And yes…<br> <strong>you’ll save hours of your life</strong></p><h3>Final Takeaway</h3><blockquote><strong><em>Convention over Configuration is not something you code — it’s something you understand and respect.</em></strong></blockquote><p>Once you understand it development becomes enjoyable.</p><h3>Connect with me</h3><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62cd6f2bc490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you confused between IoC and DI in Spring Boot?]]></title>
            <link>https://medium.com/@suryawanshisuraj2681/are-you-confused-between-ioc-and-di-in-spring-boot-da5757430850?source=rss-d634efc952bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/da5757430850</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Suraj Suryawanshi]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 18:24:17 GMT</pubDate>
            <atom:updated>2026-01-29T18:24:17.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_cgYlubAgsIMY2YJxlDhQ.jpeg" /></figure><p>One of the most confusing things about Spring Boot is how little code you write to make things work.</p><p><em>No object creation.<br> No dependency wiring.<br> No manual setup.</em></p><p>And yet — controllers get services, services get repositories, and your app runs perfectly.</p><p>This isn’t accidental. It’s the result of <strong>Inversion of Control (IoC)</strong> powered by <strong>Dependency Injection (DI)</strong>.</p><p>Most developers use these concepts every day without fully understanding them.</p><p>In this article, we’ll break it down clearly:</p><ul><li>What IoC really means</li><li>What DI is</li><li>How IoC and DI are related</li><li>Who manages IoC and who manages DI</li><li>Types of DI in Spring Boot</li><li>Why some types are recommended and others are discouraged</li></ul><p>No buzzwords. Just clarity.</p><h3>What Is Inversion of Control (IoC)?</h3><p><strong>Inversion of Control is a design principle</strong>, not a framework feature.</p><blockquote><strong><em>IoC means your application code does not control object creation and lifecycle — the framework does.</em></strong></blockquote><h3>Traditional (Without IoC)</h3><pre>class OrderService {<br>    private PaymentService paymentService = new PaymentService();<br>}</pre><p>Here:</p><ul><li>Your code decides <strong>what</strong> to create</li><li>Your code decides <strong>when</strong> to create it</li><li>Your code controls everything</li></ul><p>This leads to:</p><ul><li>Tight coupling</li><li>Hard-to-test code</li><li>Difficult changes later</li></ul><h3>With IoC (Spring Boot)</h3><pre>@Service<br>class OrderService {<br><br>    private final PaymentService paymentService;<br><br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>Notice:</p><ul><li>No new PaymentService()</li><li>OrderService does not care <em>how</em> PaymentService is created</li></ul><p><strong>Control is inverted</strong><br> The framework (Spring) controls object creation and wiring.</p><h3>Who Manages IoC in Spring Boot?</h3><p><strong>Spring Container</strong> manages IoC.</p><p>More specifically:</p><ul><li>ApplicationContext</li><li>BeanFactory</li></ul><h3>What the Spring Container Does</h3><ul><li>Creates objects (beans)</li><li>Manages lifecycle</li><li>Resolves dependencies</li><li>Injects dependencies</li><li>Controls startup &amp; shutdown</li></ul><h3>What Is Dependency Injection (DI)?</h3><p><strong>Dependency Injection is a design pattern</strong>.</p><blockquote><strong><em>DI is the technique used to provide dependencies from outside instead of creating them inside a class.</em></strong></blockquote><p>So instead of:</p><pre>new PaymentService();</pre><p>You receive it from outside:</p><pre>public OrderService(PaymentService paymentService) {<br>    this.paymentService = paymentService;<br>}</pre><h3>Relationship Between IoC and DI</h3><p>This is the most important mental model:</p><pre>IoC = Principle (idea)<br>DI  = Pattern (implementation)</pre><ul><li>IoC answers: <strong>Who controls object creation?</strong></li><li>DI answers: <strong>How are dependencies provided?</strong></li></ul><p>Spring achieves <strong>IoC using DI</strong></p><h3>Who Manages DI in Spring Boot?</h3><ul><li><strong>Spring Container</strong> manages DI</li><li>You only declare dependencies</li><li>Spring resolves and injects them</li></ul><p>You don’t call DI.<br> You <strong>declare intent</strong>, Spring does the rest.</p><h3>Types of Dependency Injection in Spring Boot</h3><p>Spring supports <strong>three types of DI</strong>:</p><ol><li>Constructor Injection (Recommended)</li><li>Setter Injection (Conditional)</li><li>Field Injection (Discouraged)</li></ol><p>Let’s understand each with examples and reasons.</p><h3>1. Constructor Injection (Recommended)</h3><h4>Example</h4><pre>@Service<br>class OrderService {<br><br>    private final PaymentService paymentService;<br><br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><h4>Why Constructor Injection Is Best</h4><ul><li>Dependencies are <strong>mandatory</strong></li><li>Object is <strong>always fully initialized</strong></li><li>Supports <strong>immutability</strong> (final)</li><li>Easy to <strong>unit test without Spring</strong></li><li>Dependencies are <strong>explicit</strong></li><li>Recommended by Spring team</li></ul><h4>Unit Test Example</h4><pre>PaymentService mock = mock(PaymentService.class);<br><br>OrderService service = new OrderService(mock);</pre><p>No Spring context. Clean and fast.</p><h3>2. Setter Injection (Use Carefully)</h3><h4>Example</h4><pre>@Service<br>class OrderService {<br><br>    private PaymentService paymentService;<br><br>    @Autowired<br>    public void setPaymentService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><h4>Why Setter Injection Is Only Sometimes OK</h4><ul><li>Dependency is optional</li><li>Object can exist in <strong>partially initialized state</strong></li><li>Cannot use final</li><li>Easy to forget injection</li></ul><h4>When Setter Injection Makes Sense</h4><ul><li>Truly optional dependencies</li><li>Feature toggles</li><li>Legacy code</li><li>Configurable behavior</li></ul><p>Example:</p><pre>@Autowired(required = false)<br>public void setDiscountService(DiscountService discountService) {<br>    this.discountService = discountService;<br>}</pre><h3>3. Field Injection (Not Recommended)</h3><h4>Example</h4><pre>@Service<br>class OrderService {<br>    @Autowired<br>    private PaymentService paymentService;<br>}</pre><h4>Why Field Injection Is Discouraged</h4><ul><li>Hidden dependencies</li><li>Breaks encapsulation (reflection)</li><li>Cannot be immutable</li><li>Hard to test</li><li>Encourages poor design</li></ul><h4>Testing Becomes Ugly</h4><p>You either:</p><ul><li>Use reflection</li><li>Or load Spring context</li></ul><pre>@SpringBootTest<br>class OrderServiceTest {<br>    @MockBean<br>    PaymentService paymentService;<br>}</pre><p>This turns unit tests into integration tests.</p><p>Field injection <em>works</em>, but <strong>working is not the same as good design</strong>.</p><h3>Comparison Summary</h3><pre>| Injection Type | Recommended  | Reason                        |<br>| -------------- | ------------ | ----------------------------- |<br>| Constructor    |   Yes        | Safe, explicit, testable      |<br>| Setter         |   Sometimes  | Optional dependencies         |<br>| Field          |   No         | Hidden, fragile, hard to test |</pre><h3>Final Takeaway</h3><ul><li><strong>IoC</strong> is about <em>who controls object creation</em></li><li><strong>DI</strong> is about <em>how dependencies are provided</em></li><li>Spring Boot implements <strong>IoC using DI</strong></li><li>Constructor injection is the <strong>cleanest and safest</strong></li><li>Setter injection is <strong>situational</strong></li><li>Field injection should be <strong>avoided in production code</strong></li></ul><p>Once you truly understand this, Spring Boot stops feeling magical — and starts feeling <strong>elegant</strong>.</p><h3>If you liked this article:</h3><ul><li>Follow me for more Spring &amp; Flutter deep dives</li><li>Clap if this clarified IoC vs DI for you</li><li>Comment if you want a follow-up on <strong>IoC, DI in Flutter</strong></li></ul><h3>Connect with me</h3><p><a href="https://www.linkedin.com/in/suraj-suryawanshi-921901211/">https://www.linkedin.com/in/suraj-suryawanshi-921901211/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da5757430850" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>