<?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 Ketul Malwana on Medium]]></title>
        <description><![CDATA[Stories by Ketul Malwana on Medium]]></description>
        <link>https://medium.com/@ketulm8?source=rss-54f111628457------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uA_jbuSNFjLS2i9W.jpg</url>
            <title>Stories by Ketul Malwana on Medium</title>
            <link>https://medium.com/@ketulm8?source=rss-54f111628457------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:52:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ketulm8/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[What Does “Widgets Are Cheap” Mean in Flutter?]]></title>
            <link>https://medium.com/@ketulm8/what-does-widgets-are-cheap-mean-in-flutter-ab654d496f18?source=rss-54f111628457------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab654d496f18</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-performance]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[Ketul Malwana]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 06:58:05 GMT</pubDate>
            <atom:updated>2026-07-09T06:58:05.763Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been learning Flutter for some time, you have probably heard this sentence:</p><blockquote><em>“Widgets are cheap.”</em></blockquote><p>At first, this sounds confusing. If widgets are the building blocks of the UI, how can they be cheap? Does it mean we can rebuild the whole UI again and again without worrying about performance?</p><p>Not exactly.</p><p>In Flutter, widgets are cheap because they are mostly lightweight configuration objects. A widget only describes what the UI should look like.</p><p>For example:</p><pre>Text(&#39;Hello&#39;)<br>Container(color: Colors.red)<br>MyProfileCard(user: user)</pre><p>These widgets are not the actual UI being drawn on the screen. They are just descriptions.</p><p>Flutter internally has a deeper structure:</p><pre>Widget  →  Element  →  RenderObject<br>cheap      lifecycle   layout/paint<br>           manager     heavy work</pre><p>The widget is the lightweight part. The heavier parts are the Element and RenderObject, which handle lifecycle, layout, painting, and actual rendering.</p><p>When setState() is called, Flutter may rebuild the widget tree. But that does not mean Flutter destroys and recreates the entire UI from scratch. Instead, Flutter compares the new widgets with the existing element tree and reuses as much as possible.</p><p>For example, if this widget:</p><pre>Text(&#39;1&#39;)</pre><p>changes to:</p><pre>Text(&#39;2&#39;)</pre><p>Flutter sees that the widget type is still Text and it is in the same position. So it can reuse the existing element and render object, then simply update the displayed text.</p><p>That is what makes Flutter efficient.</p><p>But there is one important warning:</p><p><strong>Widgets are cheap. Expensive work inside </strong><strong>build() is not cheap.</strong></p><p>This is fine:</p><pre>Widget build(BuildContext context) {<br>  return Text(user.name);<br>}</pre><p>But this is not:</p><pre>Widget build(BuildContext context) {<br>  final result = expensiveSorting(hugeList);<br>  final data = callApi();</pre><pre>  return MyWidget(result);<br>}</pre><p>The widget object may be cheap, but sorting a huge list or calling an API inside build() is not.</p><p>A common mistake is doing this:</p><pre>FutureBuilder(<br>  future: fetchUser(),<br>  builder: ...<br>)</pre><p>If the build method runs again, this can create a new future and may trigger the API call again.</p><p>A better approach is to create the future once:</p><pre>late Future&lt;User&gt; userFuture;</pre><pre>@override<br>void initState() {<br>  super.initState();<br>  userFuture = fetchUser();<br>}</pre><pre>@override<br>Widget build(BuildContext context) {<br>  return FutureBuilder(<br>    future: userFuture,<br>    builder: ...<br>  );<br>}</pre><p>So the real meaning of “widgets are cheap” is:</p><p>Do not be afraid of rebuilding widgets. Flutter is designed for frequent rebuilds. But keep your build methods fast, simple, and free from heavy work.</p><p>Using const widgets can also help because Flutter can reuse the same widget instance:</p><pre>const Text(&#39;Submit&#39;)</pre><p>But const is not a magic performance solution. The bigger wins usually come from writing clean build methods, avoiding unnecessary computation, splitting large widgets into smaller widgets, and managing state properly.</p><p>In simple words:</p><blockquote><em>Rebuilding widgets is cheap.<br>Doing expensive work during rebuild is not.</em></blockquote><p>That is the correct way to understand “widgets are cheap” in Flutter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab654d496f18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Guessing CORS: The Only Guide You Need to Master It]]></title>
            <link>https://medium.com/@ketulm8/stop-guessing-cors-the-only-guide-you-need-to-master-it-5c333c50d4a6?source=rss-54f111628457------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c333c50d4a6</guid>
            <category><![CDATA[cross-origin-resource]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[browsers]]></category>
            <dc:creator><![CDATA[Ketul Malwana]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 02:37:38 GMT</pubDate>
            <atom:updated>2026-04-21T02:37:38.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PwUgFIbWoSdDfUmm_9PPg.jpeg" /></figure><p>We’ve all been there. You write some frontend code, you make an API call, and suddenly your console is bleeding red.</p><blockquote><em>Access to fetch at &#39;http://api.yoursite.com&#39; from origin &#39;http://localhost:3000&#39; has been blocked by CORS policy.</em></blockquote><p>Panic sets in. You Google the error. You copy-paste app.use(cors()) into your backend. Sometimes it works, sometimes it doesn’t. You cross your fingers and move on.</p><p>But you don’t actually know <em>why</em> it worked.</p><p>Today, we are going to stop guessing. To master CORS (Cross-Origin Resource Sharing), you have to unlearn one massive misconception right now:</p><p>CORS is not a server security feature. CORS is a browser enforcement mechanism.</p><p>If you understand that single sentence, the rest of CORS becomes incredibly logical. Let’s break it down using plain English and real-world scenarios.</p><h3>What the hell is an “Origin”?</h3><p>Before we can share resources across origins, we need to know what an origin is.</p><p>An Origin is simply a 3-part address. It consists of:</p><ol><li>The Protocol: http:// or https://</li><li>The Domain: example.com</li><li>The Port: Usually invisible (like 80 or 443), but it’s there. Or it might be explicit, like :3000.</li></ol><p>Here is the golden rule of the web: If even ONE of those three parts is different, it is a completely different Origin.</p><ul><li>https://example.com vs https://example.com/about 👉 Same Origin (Just different rooms in the same house)</li><li>https://example.com vs http://example.com 👉 Different Origin (Different protocol!)</li><li>https://example.com vs https://api.example.com 👉 Different Origin (Different domain!)</li><li>https://example.com vs https://example.com:3000 👉 Different Origin (Different port!)</li></ul><p>Keep this in mind. It’s the foundation of everything.</p><h3>The Browser Security Guard and the Permission Slip</h3><p>Imagine every website is a house. Web browsers (like Chrome) have a built-in, heavily armed Security Guard.</p><p>The Security Guard has one job: Enforce the Same-Origin Policy. This policy states that JavaScript running inside House A is strictly forbidden from reading the private files of House B.</p><p><em>Why?</em> Imagine you log into your bank at https://bank.com. The bank gives your browser a session cookie. Now, you open a new tab and visit https://evil-hacker.com. Without the Security Guard, the hacker&#39;s JavaScript could silently reach into https://bank.com, grab your cookie, and read your balance.</p><p>To prevent this, the Security Guard steps in. If JavaScript from evil-hacker.com asks for data from bank.com, the guard blocks it.</p><p>But wait, how do legitimate websites work? How does https://my-blog.com get data from <a href="https://api.weather.com/?">https://api.weather.com?</a></p><p>Enter CORS.</p><p>CORS is simply a Permission Slip. When the Security Guard blocks a request, the server can hand the guard a slip of paper that says: <em>“Hey, I know this looks sketchy, but I explicitly give </em><em>https://my-blog.com permission to read my data.&quot;</em></p><p>That permission slip is an HTTP Header called Access-Control-Allow-Origin.</p><h3>Scenario 1: The Bank Robbery (How CORS protects you)</h3><p>Let’s look at how CORS saves the day.</p><ol><li>You are logged into <a href="https://my-bank.com./">https://my-bank.com.</a></li><li>You open a new tab and visit <a href="https://evil-hacker.com./">https://evil-hacker.com.</a></li><li>The hacker’s JavaScript tries to secretly fetch your bank balance.</li></ol><p>The Conversation inside your Browser:</p><ul><li>JavaScript: “Hey Security Guard, go get the data from my-bank.com.&quot;</li><li>Security Guard: “Hold up. You live in evil-hacker.com, but you&#39;re asking for data from my-bank.com. Different Origins. I will ask the bank for the data, but I&#39;m enforcing CORS.&quot;</li><li><em>(The Guard asks the bank. The bank sends back the data: “$50,000”.)</em></li><li>Security Guard: “Did the bank include a Permission Slip for evil-hacker.com? Let me check the headers... No. There is no Access-Control-Allow-Origin header for this origin.&quot;</li><li>Security Guard: <em>(To JavaScript)</em> “Nope. Blocked.”</li></ul><p>Result: The hacker gets nothing. Notice what happened: The bank still received the request and sent the data back. The Security Guard just intercepted it before handing it to the hacker’s JavaScript.</p><h3>Scenario 2: The Localhost Trap (How you actually fix it)</h3><p>You are building a new app. You run your React frontend on http://localhost:3000. You run your Node backend on http://localhost:8000. Different ports = Different Origins.</p><p>You make a fetch call, and boom: CORS error.</p><p>How to fix it: You are the owner of the backend. You <em>want</em> your frontend to read your data. So, you need to teach your backend to hand out Permission Slips.</p><p>If you are using Node/Express, you install the cors package, or you manually add the header to your responses:</p><p>javascript</p><p>app.use((req, res, next) =&gt; {</p><p>res.header(“Access-Control-Allow-Origin”, “http://localhost:3000&quot;); // The Permission Slip</p><p>next();</p><p>});</p><p>The Next Attempt:</p><ul><li><em>(The Guard asks the backend for data. The backend sends back the data AND the </em><em>Access-Control-Allow-Origin header.)</em></li><li>Security Guard: “I see a Permission Slip! It explicitly allows http://localhost:3000. I will hand this data to the frontend.&quot;</li></ul><p>Result: It works. And you know exactly why.</p><h3>Scenario 3: The “It Works in Postman!” Lie (The Sneaky Preflight)</h3><p>This is where 90% of developers lose their minds.</p><p>You are trying to send a POST request to your API. You are sending JSON data (Content-Type: application/json).</p><p>You test it in Postman. It works perfectly. You test it in your frontend. CORS error.</p><p>Why? Because Postman is not a web browser. Postman doesn’t have a Security Guard. It just slams requests against servers. Browsers, however, have a special rule for “complex” requests (like sending JSON).</p><p>When a browser sees you trying to send JSON, the Security Guard says: <em>“Whoa, sending data changes things. I need to ask the server for permission BEFORE I send the actual data.”</em></p><p>This is called a Preflight Request.</p><ol><li>The browser sends a special OPTIONS request to the server first. It asks: <em>&quot;Hey server, I plan to send a POST request with JSON headers. Are you cool with that?&quot;</em></li><li>Your server, which only knows how to handle POST requests, receives the OPTIONS request, gets confused, and returns an error.</li><li>The Security Guard sees the error and says: <em>“The server doesn’t know how to handle this. I’m blocking the real POST request. CORS Error.”</em></li></ol><p>How to fix it: You have to teach your server to answer the OPTIONS preflight question. You need to hand out <em>two</em> Permission Slips:</p><p>javascript</p><blockquote>app.use((req, res, next) =&gt; {</blockquote><blockquote>res.header(“Access-Control-Allow-Origin”, “http://localhost:3000&quot;);</blockquote><blockquote>// Answer the Preflight questions:</blockquote><blockquote>res.header(“Access-Control-Allow-Methods”, “GET, POST, PUT, DELETE”);</blockquote><blockquote>res.header(“Access-Control-Allow-Headers”, “Content-Type”); // Allowing JSON!</blockquote><blockquote>// Tell the browser to cache this preflight for 24 hours so it doesn’t ask every time</blockquote><blockquote>res.header(“Access-Control-Max-Age”, “86400”);</blockquote><blockquote>// IMPORTANT: End the cycle here for OPTIONS requests!</blockquote><blockquote>if (req.method === “OPTIONS”) {</blockquote><blockquote>return res.sendStatus(200);</blockquote><blockquote>}</blockquote><blockquote>next();</blockquote><blockquote>});</blockquote><p>Once the server properly answers the OPTIONS request, the Security Guard says, <em>&quot;Okay, you may now send the real POST request.&quot;</em></p><h3>The Master-Level Gotcha: Cookies and Wildcards</h3><p>There is one trap that catches senior developers off guard.</p><p>Let’s say you want to send cookies (like a session token) along with your cross-origin request. On your frontend, you set fetch(url, { credentials: &#39;include&#39; }).</p><p>On your backend, you get lazy and use a wildcard to allow everyone: res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);</p><p>Result: CORS Error.</p><p>The Rule: When you are dealing with Credentials (Cookies, Authorization headers), the browser forbids the use of the wildcard *.</p><p>To fix it, you must explicitly state the exact origin, AND you must add another specific permission slip:</p><p>javascript</p><blockquote>const allowedOrigin = “http://localhost:3000&quot;;</blockquote><blockquote>app.use((req, res, next) =&gt; {</blockquote><blockquote>// Must be explicit, no wildcards allowed with credentials!</blockquote><blockquote>res.header(“Access-Control-Allow-Origin”, allowedOrigin);</blockquote><blockquote>res.header(“Access-Control-Allow-Credentials”, “true”); // The magic ticket for cookies</blockquote><blockquote>// … rest of your headers</blockquote><blockquote>});</blockquote><h3>TL;DR (The Cheat Sheet)</h3><ol><li>Different Protocol, Domain, or Port = Different Origin.</li><li>Browsers block cross-origin requests by default to protect users from malicious scripts.</li><li>CORS is not server security. It’s a permission slip the server gives to the browser.</li><li>The slip is the header: Access-Control-Allow-Origin.</li><li>If it works in Postman but not the browser, it’s a CORS issue.</li><li>Sending JSON? The browser will send an OPTIONS preflight request first. Your server must handle it.</li><li>Sending Cookies? You cannot use * for the origin, and you must include Access-Control-Allow-Credentials: true.</li></ol><p>Stop fearing the red text. The browser’s Security Guard isn’t your enemy; it’s just doing its job. Now, you know exactly how to hand it the right permission slip.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c333c50d4a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Image Caching: Why Your Updated Images Won’t Display (And How to Fix It)]]></title>
            <link>https://medium.com/@ketulm8/flutter-image-caching-why-your-updated-images-wont-display-and-how-to-fix-it-5e9aa1105155?source=rss-54f111628457------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e9aa1105155</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ketul Malwana]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 09:29:43 GMT</pubDate>
            <atom:updated>2026-02-05T09:29:43.451Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem That Stumped Me for Hours</h3><p>Picture this: You’ve built a beautiful Flutter app with two screens. Screen A displays a ListView of items, each with a thumbnail image. Screen B has a canvas where users can draw or edit something. When users navigate back from Screen B to Screen A, you save the canvas as an image to SQLite and update the ListView.</p><p>Everything works perfectly… except the thumbnails don’t update.</p><p>If you’ve encountered this frustrating issue, you’re not alone. Let me walk you through what’s happening under the hood and how to fix it properly.</p><h3>Understanding the Scenario</h3><p>Here’s the typical flow:</p><ol><li><strong>Screen A</strong>: Displays a ListView with thumbnail images loaded using Image.file()</li><li><strong>Screen B</strong>: Contains a canvas for drawing/editing</li><li><strong>Navigation back to Screen A</strong>:</li></ol><ul><li>Save the canvas as an image to SQLite local database</li><li>Update the ListView</li><li><strong>Expected</strong>: Thumbnails should reflect the new images</li><li><strong>Reality</strong>: Old thumbnails still display</li></ul><h3>Why This Happens: Flutter’s Image Caching Mechanism</h3><p>Flutter’s Image widget includes a sophisticated caching system to improve performance. When you use Image.file(), Flutter caches the image in memory using the file path as the cache key.</p><p>Here’s the catch: <strong>Even if you modify or replace the file, Flutter sees the same file path and serves the cached version instead of reading the updated file from disk.</strong></p><p>This is actually a feature, not a bug! It prevents unnecessary disk I/O operations and improves app performance. But in our case, it’s working against us.</p><h3>The Technical Details</h3><p>When you use Image.file(File(&#39;path/to/image.png&#39;)), Flutter:</p><ol><li>Creates a FileImage ImageProvider</li><li>Uses the file path as the cache key</li><li>Checks if an image with that key exists in the ImageCache</li><li>If found, returns the cached image (even if the file has changed!)</li><li>If not found, loads from disk and caches it</li></ol><h3>The Solution: Two-Step Process</h3><p>To properly update images that have been modified, you need to:</p><h3>Step 1: Evict the Image from Cache</h3><p>Before updating your UI, explicitly remove the old image from Flutter’s cache:</p><pre>// Create the ImageProvider for the file<br>final imageProvider = FileImage(File(imagePath));</pre><pre>// Evict it from the cache<br>await imageProvider.evict();</pre><p>The evict() method removes the image from both the ImageCache and any other caches maintained by the ImageProvider.</p><h3>Step 2: Use ValueKey to Force Widget Rebuild</h3><p>Even after evicting the cache, Flutter’s widget tree might not rebuild the Image widget if it thinks nothing has changed. We need to give Flutter a reason to treat this as a “new” widget:</p><pre>Image.file(<br>  File(imagePath),<br>  key: ValueKey(imagePath + DateTime.now().toString()),<br>  // or use a timestamp/version from your database<br>  // key: ValueKey(&#39;$imagePath-${item.lastModified}&#39;),<br>)</pre><p>The ValueKey ensures that when the key changes, Flutter treats it as a completely new widget and rebuilds it from scratch.</p><h3>Complete Implementation Example</h3><p>Here’s a practical implementation showing both screens:</p><h3>Screen A: ListView with Thumbnails</h3><pre>class ScreenA extends StatefulWidget {<br>  @override<br>  _ScreenAState createState() =&gt; _ScreenAState();<br>}</pre><pre>class _ScreenAState extends State&lt;ScreenA&gt; {<br>  List&lt;ImageItem&gt; items = [];</pre><pre>  @override<br>  void initState() {<br>    super.initState();<br>    _loadItems();<br>  }</pre><pre>  Future&lt;void&gt; _loadItems() async {<br>    // Load items from SQLite<br>    final loadedItems = await DatabaseHelper.instance.getItems();<br>    setState(() {<br>      items = loadedItems;<br>    });<br>  }</pre><pre>  Future&lt;void&gt; _navigateToScreenB(ImageItem item) async {<br>    final result = await Navigator.push(<br>      context,<br>      MaterialPageRoute(<br>        builder: (context) =&gt; ScreenB(item: item),<br>      ),<br>    );</pre><pre>    // If image was updated, refresh the specific item<br>    if (result == true) {<br>      await _refreshItem(item);<br>    }<br>  }</pre><pre>  Future&lt;void&gt; _refreshItem(ImageItem item) async {<br>    // Step 1: Evict the old image from cache<br>    final imageProvider = FileImage(File(item.imagePath));<br>    await imageProvider.evict();</pre><pre>    // Step 2: Reload the item from database<br>    final updatedItem = await DatabaseHelper.instance.getItem(item.id);<br>    <br>    // Step 3: Update state to trigger rebuild with new ValueKey<br>    setState(() {<br>      final index = items.indexWhere((i) =&gt; i.id == item.id);<br>      if (index != -1) {<br>        items[index] = updatedItem;<br>      }<br>    });<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;My Images&#39;)),<br>      body: ListView.builder(<br>        itemCount: items.length,<br>        itemBuilder: (context, index) {<br>          final item = items[index];<br>          return ListTile(<br>            leading: Image.file(<br>              File(item.imagePath),<br>              key: ValueKey(&#39;${item.imagePath}-${item.lastModified}&#39;),<br>              width: 50,<br>              height: 50,<br>              fit: BoxFit.cover,<br>              errorBuilder: (context, error, stackTrace) {<br>                return Icon(Icons.error);<br>              },<br>            ),<br>            title: Text(item.name),<br>            onTap: () =&gt; _navigateToScreenB(item),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>Screen B: Canvas Editor</h3><pre>class ScreenB extends StatefulWidget {<br>  final ImageItem item;</pre><pre>  ScreenB({required this.item});</pre><pre>  @override<br>  _ScreenBState createState() =&gt; _ScreenBState();<br>}</pre><pre>class _ScreenBState extends State&lt;ScreenB&gt; {<br>  final GlobalKey _canvasKey = GlobalKey();<br>  // Your canvas implementation here...</pre><pre>  Future&lt;void&gt; _saveAndGoBack() async {<br>    // 1. Capture the canvas as an image<br>    final boundary = _canvasKey.currentContext!.findRenderObject() <br>        as RenderRepaintBoundary;<br>    final image = await boundary.toImage(pixelRatio: 3.0);<br>    final byteData = await image.toByteData(format: ImageByteFormat.png);<br>    final bytes = byteData!.buffer.asUint8List();</pre><pre>    // 2. Save to file<br>    final file = File(widget.item.imagePath);<br>    await file.writeAsBytes(bytes);</pre><pre>    // 3. Update database with new timestamp<br>    await DatabaseHelper.instance.updateItem(<br>      widget.item.id,<br>      lastModified: DateTime.now().millisecondsSinceEpoch,<br>    );</pre><pre>    // 4. Return true to indicate image was updated<br>    Navigator.pop(context, true);<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Edit Canvas&#39;),<br>        actions: [<br>          IconButton(<br>            icon: Icon(Icons.save),<br>            onPressed: _saveAndGoBack,<br>          ),<br>        ],<br>      ),<br>      body: RepaintBoundary(<br>        key: _canvasKey,<br>        child: CustomPaint(<br>          // Your canvas implementation<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Database Model</h3><pre>class ImageItem {<br>  final int id;<br>  final String name;<br>  final String imagePath;<br>  final int lastModified; // Timestamp for cache busting</pre><pre>  ImageItem({<br>    required this.id,<br>    required this.name,<br>    required this.imagePath,<br>    required this.lastModified,<br>  });</pre><pre>  Map&lt;String, dynamic&gt; toMap() {<br>    return {<br>      &#39;id&#39;: id,<br>      &#39;name&#39;: name,<br>      &#39;imagePath&#39;: imagePath,<br>      &#39;lastModified&#39;: lastModified,<br>    };<br>  }</pre><pre>  factory ImageItem.fromMap(Map&lt;String, dynamic&gt; map) {<br>    return ImageItem(<br>      id: map[&#39;id&#39;],<br>      name: map[&#39;name&#39;],<br>      imagePath: map[&#39;imagePath&#39;],<br>      lastModified: map[&#39;lastModified&#39;],<br>    );<br>  }<br>}</pre><h3>Alternative Approaches</h3><h3>1. Using a Cache-Busting Query Parameter</h3><p>Some developers add a timestamp to the file path (though this doesn’t work with file paths):</p><p>dart</p><pre>// This works for network images:<br>Image.network(&#39;$url?timestamp=${DateTime.now().millisecondsSinceEpoch}&#39;)</pre><pre>// For files, use ValueKey instead</pre><h3>2. Disabling Cache Entirely (Not Recommended)</h3><p>You could create a custom ImageProvider that doesn’t cache:</p><p>dart</p><pre>class NoCacheFileImage extends FileImage {<br>  NoCacheFileImage(File file) : super(file);</pre><pre>  @override<br>  ImageStreamCompleter load(FileImage key, DecoderCallback decode) {<br>    return super.load(key, decode);<br>  }</pre><pre>  @override<br>  Future&lt;bool&gt; evict({ImageCache? cache}) async =&gt; true;<br>}</pre><p>However, this hurts performance and should be avoided unless absolutely necessary.</p><h3>3. Using a Version Number in Database</h3><p>Instead of timestamps, maintain a version number:</p><p>dart</p><pre>Image.file(<br>  File(item.imagePath),<br>  key: ValueKey(&#39;${item.imagePath}-v${item.version}&#39;),<br>)</pre><p>Increment the version each time the image is updated.</p><h3>Best Practices</h3><ol><li><strong>Always evict before updating</strong>: Make cache eviction part of your update workflow</li><li><strong>Use meaningful keys</strong>: Include identifiers that change when content changes (timestamp, version, hash)</li><li><strong>Handle errors gracefully</strong>: Use errorBuilder to show fallback UI if image loading fails</li><li><strong>Consider memory</strong>: Don’t keep too many large images in ListView without proper cleanup</li><li><strong>Test thoroughly</strong>: Verify images update correctly after rotation, app restart, etc.</li></ol><h3>Common Pitfalls to Avoid</h3><ol><li><strong>Forgetting to await evict()</strong>: The eviction is asynchronous</li></ol><p>dart</p><pre>// Wrong<br>imageProvider.evict(); // Missing await</pre><pre>// Correct<br>await imageProvider.evict();</pre><p><strong>2. Using the same ValueKey</strong>: The key must change to trigger rebuild</p><p>dart</p><pre>// Wrong - key never changes<br>key: ValueKey(imagePath)</pre><pre>// Correct - key changes with content<br>key: ValueKey(&#39;$imagePath-${item.lastModified}&#39;)</pre><p><strong>3. Evicting but not rebuilding</strong>: You need both steps</p><p>dart</p><pre>// Incomplete - missing ValueKey<br>await FileImage(File(path)).evict();<br>setState(() {});<br>// Image might still not update without new ValueKey</pre><h3>Performance Considerations</h3><p>Cache eviction and forced rebuilds have performance implications:</p><ul><li><strong>Evicting</strong>: Minimal overhead, just removes from cache</li><li><strong>Reloading</strong>: Reading from disk is slower than cache</li><li><strong>Rebuilding</strong>: Widget rebuild is generally fast</li></ul><p>For a small ListView (&lt; 100 items), this approach works perfectly. For larger lists:</p><ul><li>Consider lazy eviction (only evict visible items)</li><li>Use proper ListView recycling</li><li>Implement pagination if dealing with hundreds of images</li></ul><h3>Conclusion</h3><p>Flutter’s image caching is a powerful optimization, but it can cause unexpected behavior when files are modified in place. The solution is straightforward:</p><ol><li><strong>Evict the old image</strong> from cache using ImageProvider.evict()</li><li><strong>Force widget rebuild</strong> using a dynamic ValueKey</li></ol><p>This pattern applies not just to SQLite scenarios, but any time you’re updating images at the same file path — whether from a canvas, camera, image editor, or file download.</p><p>Have you encountered this issue? How did you solve it? Drop a comment below!</p><p><strong>Tags</strong>: #Flutter #FlutterDevelopment #ImageCaching #MobileDevelopment #SQLite #StateManagement</p><p><strong>Resources</strong>:</p><ul><li><a href="https://api.flutter.dev/flutter/painting/ImageCache-class.html">Flutter ImageCache documentation</a></li><li><a href="https://api.flutter.dev/flutter/painting/ImageProvider/evict.html">ImageProvider.evict() method</a></li><li><a href="https://api.flutter.dev/flutter/foundation/ValueKey-class.html">ValueKey documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e9aa1105155" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>