<?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 Navin Prince on Medium]]></title>
        <description><![CDATA[Stories by Navin Prince on Medium]]></description>
        <link>https://medium.com/@navinprince.thegr8gossiper?source=rss-83f4b84c400f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*K8ImW40g3jJ0LaWu</url>
            <title>Stories by Navin Prince on Medium</title>
            <link>https://medium.com/@navinprince.thegr8gossiper?source=rss-83f4b84c400f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:43:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@navinprince.thegr8gossiper/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 Auto-Redirect with Countdown (Done Right)]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/%EF%B8%8F-flutter-auto-redirect-with-countdown-done-right-c8ef04750650?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ef04750650</guid>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[navigation]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 03:30:29 GMT</pubDate>
            <atom:updated>2026-02-08T03:34:28.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Auto-redirect screens (payment success, logout, session expiry) look simple, but are easy to get wrong in Flutter.<br> The goal is <strong>one navigation intent</strong>, triggered either by a <strong>timer</strong> or a <strong>button click</strong>, without breaking the navigation stack.</p><p><strong>🎯 Requirements</strong></p><ul><li>Show a live countdown (5…4…3…)</li><li>Auto-navigate to Home when countdown ends</li><li>Allow immediate navigation via button</li><li>Prevent double navigation</li><li>Clear previous routes</li></ul><p>🧠<strong> Correct Approach</strong></p><ol><li>Use a StatefulWidget</li></ol><p>2. Drive countdown using Timer.periodic</p><p>3. Centralize navigation in a single method</p><p>4. Guard navigation with a boolean flag</p><p>5. Clear stack using pushAndRemoveUntil</p><p>6. Always cancel timers in dispose()</p><p><strong>✅ Production-Safe Implementation</strong></p><pre>class RedirectToHome extends StatefulWidget {<br>  const RedirectToHome({super.key});<br><br>  @override<br>  State&lt;RedirectToHome&gt; createState() =&gt; _RedirectToHomeState();<br>}<br><br>class _RedirectToHomeState extends State&lt;RedirectToHome&gt; {<br>  int seconds = 5;<br>  Timer? timer;<br>  bool navigated = false;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    timer = Timer.periodic(const Duration(seconds: 1), (_) {<br>      if (seconds == 0) {<br>        navigate();<br>      } else {<br>        setState(() =&gt; seconds--);<br>      }<br>    });<br>  }<br><br>  void navigate() {<br>    if (navigated) return;<br>    navigated = true;<br>    timer?.cancel();<br><br>    Navigator.pushAndRemoveUntil(<br>      context,<br>      MaterialPageRoute(builder: (_) =&gt; HomePage()),<br>      (_) =&gt; false,<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    timer?.cancel();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        Text(<br>          &quot;Redirecting to home in $seconds seconds\nor tap below to go now&quot;,<br>          textAlign: TextAlign.center,<br>        ),<br>        const SizedBox(height: 40),<br>        HomeButton(title: &#39;Home&#39;, onTap: navigate),<br>      ],<br>    );<br>  }<br>}</pre><p><strong>❌ What to Avoid</strong></p><ul><li>Future.delayed() without cancellation</li><li>Navigator.pop() + push()</li><li>Multiple navigation triggers</li><li>Uncancelled timers</li></ul><p><strong>📌 Use This Pattern For</strong></p><ul><li>Order/payment success</li><li>Logout flows</li><li>Session timeout screens</li><li>Verification success pages</li></ul><h3>Takeaway</h3><p><strong>One navigation method, multiple triggers, zero side effects.</strong><br> That’s how auto-redirects should be implemented in Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*VRySO8F06lC0ovYR1hNacw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ef04750650" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Text Is Selectable in HTML but Not in Flutter?]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/why-text-is-selectable-in-html-but-not-in-flutter-167112d7bcf4?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/167112d7bcf4</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[skia]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 21:05:15 GMT</pubDate>
            <atom:updated>2026-01-08T21:05:15.742Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever built apps in both <strong>HTML/CSS</strong> and <strong>Flutter</strong>, you may have noticed a curious difference:</p><ul><li>On a web page, text is <strong>selectable by default</strong>.</li><li>In a Flutter app, text rendered with the Text widget is <strong>not selectable</strong> unless you explicitly enable it.</li></ul><p>This article explains why that happens, and how you can make Flutter text behave more like HTML text.</p><p>🖥️ How HTML Handles Text</p><ul><li>HTML text is rendered by the <strong>browser’s native text engine</strong>.</li><li>Elements like &lt;p&gt;, &lt;div&gt;, and &lt;span&gt; are part of the <strong>DOM (Document Object Model)</strong>.</li><li>Browsers automatically support text selection, copy, and accessibility features.</li><li>Developers can disable selection using CSS (user-select: none;), but the default is <strong>selectable text</strong>.</li></ul><p>📱 How Flutter Handles Text</p><ul><li>Flutter doesn’t rely on the browser’s text engine. Instead, it uses <strong>Skia</strong>, a graphics rendering engine.</li><li>A Text widget in Flutter is essentially <strong>painted pixels on a canvas</strong>.</li><li>Since it’s just drawn graphics, the framework doesn’t automatically provide selection, copy, or cursor behavior.</li></ul><p>To enable selection, Flutter provides a dedicated widget:</p><pre>SelectableText(<br>  &#39;This text can be selected and copied!&#39;,<br>  style: TextStyle(fontSize: 18),<br>)</pre><p>⚖️ Key Difference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lbLTutM0GvI466n9VDWuA.png" /><figcaption>htmlvsdart</figcaption></figure><p>Conclusion :</p><p>The difference boils down to <strong>DOM vs Canvas rendering</strong>.</p><ul><li>HTML text is selectable because browsers treat text as structured DOM elements.</li><li>Flutter text is drawn as graphics, so selection must be explicitly enabled.</li></ul><p>👉 Next time you want your Flutter app to behave like a web page, just swap Text for SelectableText.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=167112d7bcf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unmasking Bitcoin: A Journey Through Crypto’s Most-Asked Questions]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/unmasking-bitcoin-a-journey-through-cryptos-most-asked-questions-29708c4651a5?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29708c4651a5</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[satoshi-nakamoto]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 02:09:38 GMT</pubDate>
            <atom:updated>2025-10-06T02:09:38.634Z</atom:updated>
            <content:encoded><![CDATA[<p>Bitcoin has captivated the world for over a decade, but for many, its origins, mechanics, and future remain shrouded in mystery. This Q&amp;A-style post walks through some of the most common and intriguing questions surrounding the cryptocurrency, from the anonymous creator Satoshi Nakamoto to the rise of competitors like Ethereum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUycNxj7JxXXf08aCUgrPw.jpeg" /></figure><p><strong>Who is Satoshi Nakamoto, and what country is he from?</strong></p><p>Satoshi Nakamoto is the <strong>pseudonymous creator (or group of creators)</strong> of <strong>Bitcoin</strong>, the world’s first decentralized cryptocurrency. The identity and country of origin of Satoshi Nakamoto remain unknown. While the name is Japanese and a P2P Foundation profile in 2012 suggested a Japanese male, factors like flawless, idiomatic English and forum post timings inconsistent with a Japanese timezone suggest a different origin, possibly the UK or the US. Various candidates, such as Hal Finney, Nick Szabo, and Peter Todd, have been proposed over the years, but none have been definitively proven to be Satoshi.</p><p><strong>Q: Who deposits Bitcoin to Satoshi Nakamoto’s wallet address : </strong>1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa <strong>?</strong></p><p>The identity of those depositing Bitcoin into Satoshi Nakamoto’s wallet addresses remains unknown. While Bitcoin transactions are transparent and recorded on the blockchain, the people behind the addresses are anonymous. Recent deposits, including significant ones like <strong>$20,000</strong> in June 2025 and <strong>26.9 BTC</strong> in January 2024 from Binance-linked wallets, have been noted. The senders’ motives are speculative and could include tributes, accidental transfers, or marketing stunts.</p><p><strong>Q: How is Satoshi Nakamoto’s Bitcoin fortune growing?</strong></p><p>Satoshi Nakamoto’s fortune is growing primarily through the appreciation of Bitcoin’s market price, not through active trading or mining. Based on blockchain analysis, Satoshi is estimated to hold around <strong>1.1 million BTC</strong> from mining in Bitcoin’s early days. With the market price rising, the value of these untouched holdings increases. As of July 2025, with prices over <strong>$122,000</strong>, Nakamoto’s holdings were estimated to be worth <strong>$129 billion</strong>.</p><p><strong>Q: How did Satoshi Nakamoto mine Bitcoin in the early days?</strong></p><p>In Bitcoin’s early days, Satoshi Nakamoto mined using standard <strong>Central Processing Units (CPUs)</strong> on a personal computer. The mining difficulty was extremely low, and the process was far more accessible than it is today. As competition increased, miners moved to more powerful hardware like Graphics Processing Units (GPUs) and eventually to specialized Application-Specific Integrated Circuits (ASICs), which dominate the market today</p><p><strong>Q: Where is Satoshi Nakamoto now?</strong></p><p>The location and identity of Satoshi Nakamoto remain unknown. Satoshi communicated with the community until around <strong>2011</strong> before disappearing. Despite extensive investigations and theories, no one has definitively proven who Satoshi is. The creator’s anonymity is often viewed as a deliberate choice to prevent centralization of power and ensure Bitcoin’s decentralized ethos.</p><p><strong>Q: Does the government know who Satoshi Nakamoto is and keep it confidential?</strong></p><p>No government agency has publicly confirmed knowing Satoshi’s identity. While there is speculation and past investigations, US agencies have typically responded to requests for information with a “Glomar response,” neither confirming nor denying the existence of such records. Claims of government knowledge remain unproven.</p><p><strong>Q: What will happen if Satoshi Nakamoto’s identity is revealed?</strong></p><p>Revealing Satoshi’s identity would likely have significant consequences. It could cause extreme market volatility, potentially threatening Bitcoin’s decentralized nature if the creator tried to exert influence. It would also lead to legal and regulatory scrutiny for Satoshi and intense public and media attention.</p><p><strong>Q: Is there any relation between Bitcoin and blockchain technology?</strong></p><p>Yes, there is a fundamental relationship. Bitcoin is the <strong>first and most well-known application</strong> of blockchain technology. The blockchain is the distributed ledger that records and verifies all Bitcoin transactions, ensuring its security, transparency, and integrity. While Bitcoin pioneered its practical use, the concept of cryptographically linked blocks existed before its creation.</p><p><strong>Q: Were there any other crypto coins before Bitcoin?</strong></p><p>Yes, several projects predated Bitcoin, though none were fully functional or decentralized cryptocurrencies. They influenced Bitcoin’s development by introducing core ideas like digital signatures and proof-of-work. Notable examples include <strong>eCash (1990)</strong>, <strong>Hashcash (1997)</strong>, <strong>B-money (1998)</strong>, and <strong>Bit Gold (1998)</strong>.</p><p><strong>Q: Are there any active crypto coins discovered before Bitcoin?</strong></p><p>No, there are <strong>no active cryptocurrencies today that were created and launched before Bitcoin.</strong> Bitcoin, launched in January <strong>2009</strong>, is considered the first successful decentralized cryptocurrency and laid the groundwork for all subsequent altcoins.</p><p><strong>Q: Which crypto coins were discovered after Bitcoin in the early days and are still active?</strong></p><p>Several early altcoins are still active. These projects either built upon Bitcoin’s code or introduced new features and use cases. Notable examples include:</p><ul><li><strong>Namecoin (2011):</strong> The first to use blockchain for a purpose beyond payments (decentralized DNS).</li><li><strong>Litecoin (2011):</strong> A fork of Bitcoin designed for faster transaction times.</li><li><strong>XRP (2012):</strong> Created to facilitate fast, low-cost international payments.</li><li><strong>Peercoin (2012):</strong> The first to implement a Proof-of-Stake mechanism.</li><li><strong>Dogecoin (2013):</strong> Originally a satirical coin that gained a large community.</li></ul><p><strong>Q: What about ETH?</strong></p><p>Ethereum (ETH), though launched later in <strong>2015</strong>, is a distinct and highly influential cryptocurrency. It introduced <strong>smart contracts</strong>, a foundational technology for decentralized finance (DeFi), NFTs, and other decentralized applications (dApps). Unlike Bitcoin, Ethereum transitioned from a energy-intensive <strong>Proof-of-Work (PoW)</strong> system to a more efficient <strong>Proof-of-Stake (PoS)</strong> mechanism in <strong>2022</strong>.</p><p><strong>Q: How many crypto coins are there currently?</strong></p><p>The exact number of cryptocurrencies fluctuates constantly as new ones are created. While over <strong>37 million</strong> unique coins have been created throughout history, platforms like CoinMarketCap and CoinGecko track a more conservative number of <strong>actively traded</strong> ones, which is in the thousands (<strong>9,537</strong> and <strong>17,151</strong>, respectively, at the time of this post).</p><p><strong>Q: What is the worst expected future of Bitcoin?</strong></p><p>Worst-case scenarios for Bitcoin include a complete technological failure due to advances in quantum computing, a critical bug, or an irreversible hack. Governments could also unite to ban or heavily restrict its use, or a new digital currency could emerge and render Bitcoin obsolete. A permanent market crash or growing environmental backlash could also severely damage public trust and value.</p><p><strong>Q: What is Bitcoin’s most likely future?</strong></p><p>The most likely future for Bitcoin is its continued evolution as a globally recognized alternative asset, often compared to “digital gold.” It is expected to continue its long-term upward trend, driven by its scarce supply and growing institutional adoption. However, it will likely remain volatile. It is not expected to replace government-issued currencies but will instead coexist, especially as Layer-2 solutions improve its transaction speed and utility.</p><p><strong>Q: Which documentary can we watch about Bitcoin and Satoshi Nakamoto?</strong></p><p>A recent HBO documentary, released in October 2024, is a notable option. It is called <strong>“Money Electric: The Bitcoin Mystery”</strong>. The film, from Emmy-nominated director Cullen Hoback, investigates Bitcoin’s origins and explores the mystery surrounding Satoshi Nakamoto’s identity.</p><p><strong>Conclusion:</strong></p><p>This Q&amp;A provides a comprehensive overview of Bitcoin’s journey, from its mysterious origins and foundational technology to its current status and likely future. The questions reveal a complex and dynamic ecosystem where innovation, speculation, and risk coexist. As the crypto landscape continues to evolve, understanding these core concepts remains essential for navigating the future of digital assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7VVUYYlPZSvORcEnE0Q6g.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29708c4651a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing Unresponsive CupertinoSwitch or Switch in Flutter: A Smooth Toggle Experience]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/fixing-unresponsive-cupertinoswitch-or-switch-in-flutter-a-smooth-toggle-experience-ba1ca89277cf?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba1ca89277cf</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[cupertino-switch]]></category>
            <category><![CDATA[switch]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[toggle]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 15:32:02 GMT</pubDate>
            <atom:updated>2025-07-01T15:32:02.550Z</atom:updated>
            <content:encoded><![CDATA[<p>In Flutter development, ensuring a snappy, responsive UI is everything — especially when using elements like the CupertinoSwitch. I recently ran into an issue where the switch updated the backend status just fine but felt clunky or unresponsive in the UI. If you’ve ever wrapped an async block inside setState(), you might already know where this is headed.</p><p><strong>Let’s walk through the problem — and the fix.</strong></p><p>🚨 The Problem: Laggy CupertinoSwitch<br>Here’s a common implementation pattern:</p><pre>onChanged: (value) {<br>  setState(() async {<br>    _switchValue = value;<br>    if (_switchValue) {<br>      userInfoList[index][&#39;user_status&#39;] = &#39;Active&#39;;<br>      await Rest().updateUserStatus(userInfoList[index][&#39;uname&#39;], &#39;Active&#39;);<br>    } else {<br>      userInfoList[index][&#39;user_status&#39;] = &#39;Inactive&#39;;<br>      await Rest().updateUserStatus(userInfoList[index][&#39;uname&#39;], &#39;Inactive&#39;);<br>    }<br>  });<br>}</pre><p>At first glance, this seems to do the trick — until you notice that the switch feels slow or unresponsive. That’s because setState should be <em>synchronous</em>. Wrapping it in async blocks disrupts the UI’s rendering lifecycle.</p><p>✅ The Fix: Split UI and Async Logic<br>Here’s the improved version:</p><pre>onChanged: (value) {<br>  setState(() {<br>    _switchValue = value;<br>    userInfoList[index][&#39;user_status&#39;] =<br>        _switchValue ? &#39;Active&#39; : &#39;Inactive&#39;;<br>  });<br><br>  Future.microtask(() async {<br>    await Rest().updateUserStatus(<br>      userInfoList[index][&#39;uname&#39;],<br>      _switchValue ? &#39;Active&#39; : &#39;Inactive&#39;,<br>    );<br>  });<br>}</pre><p>With this approach:</p><ul><li>The UI reacts instantly.</li><li>The status update happens asynchronously <em>after</em> the UI refreshes.</li><li>You avoid any unexpected widget rebuild issues.</li></ul><p>✨ Takeaway</p><p>When using Flutter’s setState(), remember: <strong>keep it clean, keep it synchronous</strong>. Offload async tasks into separate microtasks or callbacks. It not only prevents janky UI behavior but also respects Flutter’s rendering flow.</p><p>Have you faced similar issues with setState and async logic? I’d love to hear how you tackled it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*i5slzE4zNoTMIKA2008-FQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba1ca89277cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍♂️ Flutter Tutorial: How to Show Base64 Images from a REST API Like a Pro]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/%EF%B8%8F-flutter-tutorial-how-to-show-base64-images-from-a-rest-api-like-a-pro-6707b60f5203?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6707b60f5203</guid>
            <category><![CDATA[base64decode]]></category>
            <category><![CDATA[base64-to-image]]></category>
            <category><![CDATA[base64string]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 15:09:49 GMT</pubDate>
            <atom:updated>2025-07-01T15:09:49.657Z</atom:updated>
            <content:encoded><![CDATA[<p>Displaying images in a Flutter app is simple — until you’re handed a base64 string from a backend API and things start to break. If you’ve run into decoding issues, ImageCodecException, or nothing rendering at all, this guide is for you.</p><p>In this post, I’ll show you how to reliably decode and render base64-encoded images fetched from an API — especially when they’re double-encoded or not in a standard format.</p><p>🚩 The Problem<br>Let’s say your REST API returns a list of items like this:</p><pre>{<br>  &quot;item_code&quot;: &quot;A123&quot;,<br>  &quot;label_name&quot;: &quot;Classic Shirt&quot;,<br>  &quot;color&quot;: &quot;Red&quot;,<br>  &quot;type_name&quot;: &quot;Cotton&quot;,<br>  &quot;img_1&quot;: &quot;aVZCT1J3MEtHZ29BQUFBTlNVaEVVZ0FBQU1nQ...&quot; // base64 string<br>}</pre><p>You want to display img_1 in your UI. So you try:</p><pre>Image.memory(base64Decode(item[&#39;img_1&#39;]))</pre><p>And boom — Flutter throws:</p><pre>ImageCodecException: Failed to detect image file format using the file header.</pre><p>Now what?</p><p>🛠️ The Fix: Decode Smarter, Not Harder</p><p>Turns out, some APIs <strong>double encode</strong> base64 image strings — for example, they first base64-encode the raw image bytes, then encode that again as a JSON-safe string. So what we need to do is:</p><p>1. Decode the outer base64 layer to get an inner image base64 string.</p><p>2. Strip off metadata like data:image/png;base64, if present.</p><p>3. Decode the cleaned base64 to get the real Uint8List bytes.</p><p>Here’s the magic function:</p><pre>Uint8List? decodeImage(String? base64String) {<br>  if (base64String == null || base64String.isEmpty) return null;<br>  try {<br>    final firstPass = utf8.decode(base64Decode(base64String.trim()));<br>    final cleaned = firstPass.contains(&#39;,&#39;)<br>        ? firstPass.split(&#39;,&#39;).last.trim()<br>        : firstPass.trim();<br>    return base64Decode(cleaned);<br>  } catch (e) {<br>    print(&quot;Decode failed: $e&quot;);<br>    return null;<br>  }<br>}</pre><p>🧠 Store the Image Globally (if needed)</p><p>If you’re updating the image after selecting an item (say, from a DataTable), keep the decoded bytes at the widget level:</p><pre>Uint8List? _selectedImageBytes;<br><br>onSelectChanged: (val) {<br>  setState(() {<br>    _selectedImageBytes = decodeImage(item[&#39;img_1&#39;]);<br>  });<br>}</pre><p>🖼️ Render It Like a Champ</p><pre>Container(<br>  height: 160,<br>  width: 170,<br>  color: Colors.grey.shade300,<br>  child: _selectedImageBytes != null<br>      ? Image.memory(<br>          _selectedImageBytes!,<br>          fit: BoxFit.cover,<br>          errorBuilder: (_, __, ___) =&gt; Icon(Icons.broken_image),<br>        )<br>      : Icon(Icons.image_not_supported),<br>)</pre><p>🔍 Debugging Tip<br>Want to be sure the string is actually an image?</p><pre>print(&quot;Preview: ${base64String.substring(0, 30)}&quot;);</pre><p>Look for these clues:</p><pre>iVBOR → PNG<br><br>/9j/ → JPG<br><br>R0lGOD → GIF</pre><p>If it starts with something else, it’s probably a double-encoded payload.</p><p>🎯 TL;DR</p><ul><li>Don’t trust the base64 string at face value.</li><li>Double-decode if needed.</li><li>Use Image.memory with errorBuilder to fail gracefully.</li></ul><p>Now your app will confidently render images without breaking a sweat.</p><p>If you found this helpful, give it a clap 👏 or share it with another dev who’s knee-deep in API quirks. Happy Fluttering!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*GZPHDBn_DstYDju2uxCPwQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6707b60f5203" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Store Global Variables in Flutter: The Best Approaches Explained]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/how-to-store-global-variables-in-flutter-the-best-approaches-explained-cde516badf84?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cde516badf84</guid>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 20:13:07 GMT</pubDate>
            <atom:updated>2025-02-28T20:13:07.798Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>📜 Introduction:</strong><br>Managing global variables in Flutter efficiently is crucial for maintaining state across different screens and widgets. Whether you’re working on a small app or a large-scale project, choosing the right approach can improve performance and maintainability.</p><p>In this post, we’ll explore <strong>four</strong> effective ways to store and access global variables in Flutter, ranging from simple static classes to advanced state management techniques.</p><p><strong>1️⃣ Using a Static Class (Simple &amp; Quick)</strong></p><p>This is the simplest method, ideal for small applications where you just need to store a few global values. You define a class with static variables, making it accessible anywhere in your app.</p><p>✅ <strong>Pros:</strong> Easy to implement, no dependencies<br>❌ <strong>Cons:</strong> Not reactive, no automatic UI updates</p><p>📌 <strong>Example:</strong></p><pre>class Globals {<br>  static String username = &quot;&quot;;<br>  static int cartCount = 0;<br>}</pre><p>📌 <strong>Usage:</strong></p><pre>Globals.username = &quot;Navin&quot;;  <br>print(Globals.username); // Output: Navin</pre><p><strong>2️⃣ Using a Singleton Class (One Instance Across the App)</strong></p><p>A <strong>singleton</strong> ensures only one instance of a class exists, making it a great option when you need a globally accessible object without creating multiple instances.</p><p>✅ <strong>Pros:</strong> Prevents duplicate instances, good for app-wide states<br>❌ <strong>Cons:</strong> Manual state management, not reactive</p><p>📌 <strong>Example:</strong></p><pre>class AppState {<br>  static final AppState _instance = AppState._internal();<br>  factory AppState() =&gt; _instance;<br>  AppState._internal(); // Private constructor<br><br>  String username = &quot;&quot;;<br>  int cartCount = 0;<br>}</pre><p>📌 <strong>Usage:</strong></p><pre>AppState().username = &quot;Navin&quot;;<br>print(AppState().username); // Output: Navin</pre><p><strong>3️⃣ Using GetX (Reactive &amp; Lightweight State Management)</strong></p><p>GetX is a powerful package that provides <strong>reactive global state management</strong> with minimal boilerplate. It’s best suited for apps that require <strong>real-time UI updates</strong> when global data changes.</p><p>✅ <strong>Pros:</strong> Lightweight, reactive, easy to use<br>❌ <strong>Cons:</strong> Requires an external package</p><p>📌 <strong>Installation:</strong></p><pre>dependencies:<br>  get: ^4.6.6</pre><p>📌 <strong>Example:</strong></p><pre>import &#39;package:get/get.dart&#39;;<br><br>class GlobalController extends GetxController {<br>  var username = &quot;&quot;.obs;<br>  var cartCount = 0.obs;<br>}</pre><p>📌 <strong>Usage:</strong></p><pre>final globalController = Get.put(GlobalController());<br>globalController.username.value = &quot;Navin&quot;;<br><br>print(globalController.username.value); // Output: Navin</pre><p><strong>4️⃣ Using Provider (Best for Large Apps &amp; Scalability)</strong></p><p>Provider is a recommended approach for <strong>complex applications</strong> where state management is needed across multiple widgets. It ensures efficient UI updates when global data changes.</p><p>✅ <strong>Pros:</strong> Scalable, reactive, follows Flutter’s best practices<br>❌ <strong>Cons:</strong> Requires setup, more boilerplate</p><p>📌 <strong>Installation:</strong></p><pre>dependencies:<br>  provider: ^6.1.0</pre><p>📌 <strong>Example:</strong></p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br><br>class GlobalProvider with ChangeNotifier {<br>  String _username = &quot;&quot;;<br>  int _cartCount = 0;<br><br>  String get username =&gt; _username;<br>  int get cartCount =&gt; _cartCount;<br><br>  void setUsername(String name) {<br>    _username = name;<br>    notifyListeners();<br>  }<br><br>  void updateCart(int count) {<br>    _cartCount = count;<br>    notifyListeners();<br>  }<br>}</pre><p>📌 <strong>Usage in </strong><strong>main.dart:</strong></p><pre>void main() {<br>  runApp(<br>    ChangeNotifierProvider(<br>      create: (context) =&gt; GlobalProvider(),<br>      child: MyApp(),<br>    ),<br>  );<br>}</pre><p>📌 <strong>Usage in Widgets:</strong></p><pre>Provider.of&lt;GlobalProvider&gt;(context, listen: false).setUsername(&quot;Navin&quot;);<br>print(Provider.of&lt;GlobalProvider&gt;(context).username);</pre><h3>🧐 Which One Should You Choose?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqRUM7pYM8s3hiAvoiH6pw.png" /><figcaption>Global Variables Flutter Methods</figcaption></figure><p><strong>💡 Conclusion</strong></p><p>Choosing the right global state management approach in Flutter depends on your app’s complexity. <strong>For small projects</strong>, a simple <strong>static class</strong> works well. <strong>For scalable solutions</strong>, <strong>GetX or Provider</strong> is the way to go. <strong>Singletons</strong> are useful for managing unique app-wide objects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cde516badf84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Dynamic PDF Reports in Flutter with printing and pdf Packages]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/generating-dynamic-pdf-reports-in-flutter-with-printing-and-pdf-packages-acd251ea2616?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/acd251ea2616</guid>
            <category><![CDATA[report]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[flutter-pdf]]></category>
            <category><![CDATA[invoice]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 22:02:20 GMT</pubDate>
            <atom:updated>2025-08-02T14:36:55.088Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter offers powerful libraries for creating and handling PDF files. In this post, we’ll demonstrate how to dynamically generate PDF invoices and preview them within a Flutter Web app. This tutorial uses the printing and pdf packages.This is particularly useful for applications that need to generate reports, invoices, or any other printable documents.</p><h3>Prerequisites</h3><p>Before we start, make sure you have the following packages added to your pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  pdf: ^3.10.0<br>  printing: ^5.10.0<br>  http: ^0.13.3</pre><h3>Step 1: Fetching Data</h3><p>First, we need to fetch the data that will populate our PDF invoice. In this example, we’re fetching data from a local server using an HTTP GET request.</p><pre>Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; fetchData() async {<br>  try {<br>    final response = await http.get(Uri.parse(<br>      &#39;http://192.168.1.100:8080/selectOrderItem?orderId=1&#39;,<br>    ));<br><br>    if (response.statusCode == 200 || response.statusCode == 202) {<br>      final List&lt;dynamic&gt; jsonData = json.decode(response.body);<br>      return List&lt;Map&lt;String, dynamic&gt;&gt;.from(jsonData);<br>    } else {<br>      throw Exception(&#39;Failed to load data with status code: ${response.statusCode}&#39;);<br>    }<br>  } catch (e) {<br>    throw Exception(&#39;Failed to load data: $e&#39;);<br>  }<br>}</pre><h3>Step 2: Generating the PDF</h3><p>Next, we’ll create a function to generate the PDF document. This function will use the pdf package to create a PDF with a header, purchase information, and a table of items.</p><blockquote>This is the important section because here we are designing the report. As you can see UI Tree is same as Flutter Widget Tree but here we are adding prefix “pw” before each widget. which renders the widget for pdf page. you can customise Widgets UI as per your requirement. Make sure this function return pdf.</blockquote><pre>Future&lt;pw.Document&gt; generatePdfReport(int index) async {<br>  var selectedPurchaseList = []; // local use<br>  final pdf = pw.Document();<br>  final netImage = await networkImage(&#39;https://i.postimg.cc/02xHkDLd/preview.jpg&#39;);<br><br>  selectedPurchaseList.add(purHomeList[index]);<br><br>  detailList = await Rest.getData(<br>      &#39;getPurchaseDetails?poNo=${purHomeList[index][&#39;po_no&#39;]}&#39;); // fetching detail list data corresponding to supplier (one to many relation)<br><br>  pdf.addPage(<br>    pw.Page(<br>      build: (context) =&gt; pw.Center(<br>        child: pw.Container(<br>            padding: const pw.EdgeInsets.all(8.0),<br>            decoration: pw.BoxDecoration(<br>                border: pw.Border.all(<br>              color: PdfColors.black,<br>              width: 1,<br>            )),<br>            child: pw.Column(<br>              children: [<br>                // Header Section<br>                pw.Row(<br>                  mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,<br>                  children: [<br>                    pw.Column(<br>                      crossAxisAlignment: pw.CrossAxisAlignment.start,<br>                      children: [<br>                        pw.Text(&quot;NAVINOMIX PVT LTD&quot;,<br>                            style: pw.TextStyle(<br>                                fontSize: 18,<br>                                fontWeight: pw.FontWeight.bold)),<br>                        pw.Text(&quot;Kings Landing 7609 Mckinley Ave&quot;),<br>                        pw.Text(&quot;Los Angeles,California&quot;),<br>                        pw.Text(&quot;Contact No. +91-9663627343&quot;),<br>                        pw.Text(&quot;info@navinprince.com&quot;),<br>                        pw.Text(&quot;www.navinomix.com&quot;),<br>                      ],<br>                    ),<br>                    pw.Container(<br>                      width: 70,<br>                      height: 100,<br>                      child: pw.Image(netImage),<br>                    ),<br>                  ],<br>                ),<br>                pw.SizedBox(height: 20),<br><br>                // Purchase Info<br>                pw.Row(children: [<br>                  pw.Table(<br>                    columnWidths: {<br>                      1: pw.FixedColumnWidth(130),<br>                    },<br>                    border: pw.TableBorder.all(),<br>                    children: [<br>                      ...selectedPurchaseList.map((item) =&gt; pw.TableRow(<br>                            children: [<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(&quot;Supplier Name&quot;,<br>                                    style: pw.TextStyle(<br>                                        fontWeight: pw.FontWeight.bold)),<br>                              ),<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(item[&#39;supplier_name&#39;]),<br>                              ),<br>                            ],<br>                          )),<br>                      ...selectedPurchaseList.map((item) =&gt; pw.TableRow(<br>                            children: [<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(&quot;Address&quot;,<br>                                    style: pw.TextStyle(<br>                                        fontWeight: pw.FontWeight.bold)),<br>                              ),<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(item[&#39;supplier_address2&#39;]),<br>                              ),<br>                            ],<br>                          )),<br>                      ...selectedPurchaseList.map((item) =&gt; pw.TableRow(<br>                            children: [<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(&quot;State&quot;,<br>                                    style: pw.TextStyle(<br>                                        fontWeight: pw.FontWeight.bold)),<br>                              ),<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(item[&#39;supplier_state&#39;].toString()),<br>                              ),<br>                            ],<br>                          )),<br>                    ],<br>                  ),<br>                  pw.Table(<br>                    columnWidths: {<br>                      1: pw.FixedColumnWidth(130),<br>                    },<br>                    border: pw.TableBorder.all(),<br>                    children: [<br>                      ...selectedPurchaseList.map((item) =&gt; pw.TableRow(<br>                            children: [<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(&quot;Purchase Date&quot;,<br>                                    style: pw.TextStyle(<br>                                        fontWeight: pw.FontWeight.bold)),<br>                              ),<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(item[&#39;purchase_date&#39;]),<br>                              ),<br>                            ],<br>                          )),<br>                      ...selectedPurchaseList.map((item) =&gt; pw.TableRow(<br>                            children: [<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(&quot;Purchase Name&quot;,<br>                                    style: pw.TextStyle(<br>                                        fontWeight: pw.FontWeight.bold)),<br>                              ),<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(item[&#39;purchase_name&#39;].toString()),<br>                              ),<br>                            ],<br>                          )),<br>                      ...selectedPurchaseList.map((item) =&gt; pw.TableRow(<br>                            children: [<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(&quot;TIN No.&quot;,<br>                                    style: pw.TextStyle(<br>                                        fontWeight: pw.FontWeight.bold)),<br>                              ),<br>                              pw.Padding(<br>                                padding: const pw.EdgeInsets.all(8.0),<br>                                child: pw.Text(item[&#39;supplier_tin_no&#39;].toString()),<br>                              ),<br>                            ],<br>                          )),<br>                    ],<br>                  ),<br>                ]),<br><br>                pw.Table(<br>                  border: pw.TableBorder.all(),<br>                  children: [<br>                    // Header row<br>                    pw.TableRow(<br>                      decoration: pw.BoxDecoration(color: PdfColors.indigo),<br>                      children: [<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;Description&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;HSN&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;Unit&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;Qty&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;Rate&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;Taxable Amount&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;GST %&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;GST Amt&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                        pw.Padding(<br>                          padding: const pw.EdgeInsets.all(8.0),<br>                          child: pw.Text(<br>                            &#39;Total&#39;,<br>                            style: pw.TextStyle(<br>                                fontWeight: pw.FontWeight.bold,<br>                                fontSize: 8,<br>                                color: PdfColors.white),<br>                          ),<br>                        ),<br>                      ],<br>                    ),<br>                    // Data rows<br>                    ...detailList.map(<br>                      (item) =&gt; pw.TableRow(<br>                        children: [<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(<br>                                &quot;${item[&#39;item_name&#39;]}-${item[&#39;size_inch&#39;].toString()}/${item[&#39;size_cm&#39;].toString()}-${item[&#39;color&#39;]}-${item[&#39;gsm&#39;].toString()}-${item[&#39;bf&#39;].toString()}\nMill :${item[&#39;mill_name&#39;]}\nDelivery Date : ${item[&#39;purchase_delivery_date&#39;]}&quot;,<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(item[&#39;hsn_code&#39;].toString(),<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(item[&#39;unit_name&#39;],<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(item[&#39;purchase_quantity&#39;].toString(),<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(item[&#39;purchase_rate&#39;].toString(),<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(item[&#39;purchase_taxable_amt&#39;].toString(),<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(item[&#39;purchase_gst_percent&#39;].toString(),<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(item[&#39;purchase_tax_amt&#39;].toString(),<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                          pw.Padding(<br>                            padding: const pw.EdgeInsets.all(8.0),<br>                            child: pw.Text(<br>                                (item[&#39;purchase_taxable_amt&#39;] +<br>                                        item[&#39;purchase_tax_amt&#39;])<br>                                    .toString(),<br>                                style: pw.TextStyle(fontSize: 6)),<br>                          ),<br>                        ],<br>                      ),<br>                    ),<br>                  ],<br>                ),<br>              ],<br>            )),<br>      ),<br>    ),<br>  );<br>  return pdf;<br>}</pre><p>This function creates a PDF document with a header, purchase information, and a table of items. The table includes details like description, HSN code, unit, quantity, rate, taxable amount, GST percentage, GST amount, and total. Here is the result screenshot attached :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1sZsXNgSM23eLUiwJTunQ.png" /></figure><h3>Step 3: Previewing the PDF</h3><p>Once the PDF is generated, we can preview it using the printing package. We&#39;ll create a function to show the PDF in a dialog.</p><pre>void showPdfPreview(pw.Document pdf) {<br>  showDialog(<br>    context: context,<br>    builder: (context) =&gt; AlertDialog(<br>      title: Text(&#39;PDF Preview&#39;),<br>      content: Container(<br>        width: double.maxFinite,<br>        height: 400,<br>        child: PdfPreview(<br>          build: (format) =&gt; pdf.save(),<br>          allowPrinting: false, // Disable direct printing if needed<br>          allowSharing: true, // Enable sharing<br>        ),<br>      ),<br>      actions: [<br>        TextButton(<br>          onPressed: () =&gt; Navigator.pop(context),<br>          child: Text(&#39;Close&#39;),<br>        ),<br>      ],<br>    ),<br>  );<br>}</pre><p>This function displays the PDF in a dialog with options to close the preview.</p><h3>Step 4: Putting It All Together</h3><p>Finally, we’ll tie everything together in the build method of our widget. When the user presses a button, we&#39;ll generate the PDF and show the preview.</p><pre>@override<br>Widget build(BuildContext context) {<br>  return Scaffold(<br>    appBar: AppBar(title: Text(&#39;PDF Report&#39;)),<br>    body: Center(<br>      child: ElevatedButton(<br>        onPressed: () async {<br>          final pdf = await generatePdf(data);<br>          showPdfPreview(pdf);<br>        },<br>        child: Text(&quot;Show Report&quot;),<br>      ),<br>    ),<br>  );<br>}</pre><h3>Conclusion</h3><p>In this post, we’ve covered how to fetch data from an API, generate a PDF document, and preview it in a Flutter application. This approach can be adapted to various use cases, such as generating invoices, reports, or any other printable documents. The pdf and printing packages make it easy to create and manage PDFs in Flutter, providing a powerful toolset for developers.</p><p>Feel free to customize the PDF layout and content to suit your specific needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oe6_s5lZznr0q5Iy3gCZnw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acd251ea2616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Email OTP verification using Flutter and Spring-boot backend]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/email-otp-verification-using-flutter-and-spring-boot-backend-d580b827b229?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d580b827b229</guid>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[email-verification]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 18:32:49 GMT</pubDate>
            <atom:updated>2025-01-20T18:32:49.565Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we will build an Email OTP verification system using Spring Boot for the backend and Flutter for the frontend. The system allows users to send an OTP to their email and verify it.</p><h3>Prerequisites</h3><ul><li>Basic knowledge of Spring Boot and Java.</li><li>Familiarity with Flutter and Dart.</li><li>A Gmail account for configuring SMTP settings.</li></ul><h3>Backend Implementation (Spring Boot)</h3><h3>1. Configure SMTP Settings</h3><p>Create a application.properties file and configure the SMTP settings for Gmail:</p><pre>spring.mail.host=smtp.gmail.com<br>spring.mail.port=587<br>spring.mail.username=your-email@gmail.com<br>spring.mail.password=your-email-password<br>spring.mail.properties.mail.smtp.auth=true<br>spring.mail.properties.mail.smtp.starttls.enable=true</pre><h3>2. Create the Email Service</h3><p>The EmailService class handles OTP generation and sending emails:</p><pre>package com.vpcs.espl.services;<br><br>import java.util.Random;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.mail.SimpleMailMessage;<br>import org.springframework.mail.javamail.JavaMailSender;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class EmailService {<br><br>    @Autowired<br>    private JavaMailSender mailSender;<br><br>    public String sendOtp(String toEmail) {<br>        String otp = generateOtp();<br>        SimpleMailMessage message = new SimpleMailMessage();<br>        message.setTo(toEmail);<br>        message.setSubject(&quot;Your OTP Code&quot;);<br>        message.setText(&quot;Your OTP code is: &quot; + otp);<br>        mailSender.send(message);<br>        return otp;<br>    }<br><br>    private String generateOtp() {<br>        Random random = new Random();<br>        int otp = 100000 + random.nextInt(900000);<br>        return String.valueOf(otp);<br>    }<br>}</pre><h3>3. Create the OTP Controller</h3><p>The OtpController handles API requests for sending and verifying OTPs:</p><pre>package com.vpcs.espl.controller;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.CrossOrigin;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br>import com.vpcs.espl.services.EmailService;<br><br>@RestController<br>@CrossOrigin<br>public class OtpController {<br><br>    @Autowired<br>    EmailService emailService;<br><br>    @PostMapping(&quot;/send&quot;)<br>    public String sendOtp(@RequestParam String email) {<br>        return emailService.sendOtp(email);<br>    }<br><br>    @PostMapping(&quot;/verify&quot;)<br>    public boolean verifyOtp(@RequestParam String email, @RequestParam String otp, @RequestParam String userOtp) {<br>        return otp.equals(userOtp);<br>    }<br>}</pre><h3>Frontend Implementation (Flutter)</h3><h3>1. REST API Methods</h3><p>Define methods to send and verify OTPs:</p><pre>Future&lt;String?&gt; sendOtp(String email) async {<br>  final response = await http.post(<br>    Uri.parse(&#39;$URL/send&#39;),<br>    body: {&#39;email&#39;: email},<br>  );<br><br>  if (response.statusCode == 200) {<br>    return response.body;<br>  } else {<br>    return null;<br>  }<br>}<br><br>Future&lt;bool&gt; verifyOtp(String email, String otp, String userOtp) async {<br>  final response = await http.post(<br>    Uri.parse(&#39;$URL/verify&#39;),<br>    body: {&#39;email&#39;: email, &#39;otp&#39;: otp, &#39;userOtp&#39;: userOtp},<br>  );<br><br>  return response.statusCode == 200 &amp;&amp; response.body == &#39;true&#39;;<br>}</pre><h3>2. Flutter UI Code</h3><h4>Add Controllers for Email and OTP</h4><pre>TextEditingController emailId = TextEditingController();<br>TextEditingController otp = TextEditingController();<br>String? _generatedOtp;</pre><h4>Send OTP Function</h4><pre>Future&lt;void&gt; _sendOtp() async {<br>  final email = emailId.text;<br>  final otp = await Rest().sendOtp(email);<br><br>  if (otp == null) {<br>    ScaffoldMessenger.of(context).showSnackBar(<br>      SnackBar(content: Text(&#39;Failed to send OTP to $email&#39;)),<br>    );<br>    return;<br>  }<br><br>  setState(() {<br>    _generatedOtp = otp;<br>  });<br>  ScaffoldMessenger.of(context).showSnackBar(<br>    SnackBar(content: Text(&#39;OTP sent to $email&#39;)),<br>  );<br>}</pre><h4>Verify OTP Function</h4><pre>void _verifyOtp() async {<br>  final userOtp = otp.text;<br>  if (_generatedOtp != null) {<br>    final isVerified =<br>        await Rest().verifyOtp(emailId.text, _generatedOtp!, userOtp);<br>    if (isVerified) {<br>      ScaffoldMessenger.of(context).showSnackBar(<br>        SnackBar(content: Text(&#39;OTP verified successfully!&#39;)),<br>      );<br>    } else {<br>      ScaffoldMessenger.of(context).showSnackBar(<br>        SnackBar(content: Text(&#39;Invalid OTP!&#39;)),<br>      );<br>    }<br>  }<br>}</pre><h4>UI Widgets</h4><pre>TextFormField(<br>  controller: emailId,<br>  decoration: InputDecoration(<br>    labelText: &quot;Email&quot;,<br>  ),<br>),<br>ElevatedButton(<br>  onPressed: _sendOtp,<br>  child: Text(&#39;Send OTP&#39;),<br>),<br><br>TextFormField(<br>  controller: otp,<br>  decoration: InputDecoration(<br>    labelText: &quot;Email OTP&quot;,<br>  ),<br>),<br><br>ElevatedButton(<br>  onPressed: _verifyOtp,<br>  child: Text(&#39;Verify OTP&#39;),<br>),</pre><h3>Testing the Application</h3><ol><li>Start the Spring Boot application.</li><li>Run the Flutter app on your emulator or device.</li><li>Enter your email and click “Send OTP.”</li><li>Check your email for the OTP code.</li><li>Enter the OTP in the app and click “Verify OTP.”</li></ol><h3>Conclusion</h3><p>We successfully implemented an OTP verification system using Spring Boot and Flutter. This solution can be extended for user authentication, password reset, and more. Feel free to enhance it by adding database integration for storing OTPs or using a more secure email provider.</p><figure><img alt="Email OTP veri" src="https://cdn-images-1.medium.com/max/1024/1*0u1ks2uysHwUmrfcUwmamA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d580b827b229" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Displaying SQL Database Image in Flutter using Spring Boot REST API.]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/displaying-sql-database-image-in-flutter-using-spring-boot-rest-api-110b309685f5?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/110b309685f5</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 22:19:15 GMT</pubDate>
            <atom:updated>2025-01-16T22:48:01.008Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, you’ll learn how to create a Flutter widget that fetches and displays category data along with their associated images from a SQL database using a Spring Boot REST API. We will use the API to fetch categories and Base64-encoded images, decode and render those images dynamically in the Flutter app.</p><h3>Backend Setup</h3><h3>1. SQL Tables</h3><p>Below are the SQL tables used in this example:</p><pre>desc category;<br>+-----------------+---------------------+------+-----+---------+----------------+<br>| Field           | Type                | Null | Key | Default | Extra          |<br>+-----------------+---------------------+------+-----+---------+----------------+<br>| category_id     | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |<br>| category        | varchar(50)         | NO   | UNI | NULL    |                |<br>| description     | varchar(100)        | YES  |     | NULL    |                |<br>| category_status | varchar(30)         | YES  |     | NULL    |                |<br>| for_app         | tinyint(3) unsigned | YES  |     | NULL    |                |<br>+-----------------+---------------------+------+-----+---------+----------------+<br><br><br>desc category_image;<br>+-------------------+------------------+------+-----+---------+----------------+<br>| Field             | Type             | Null | Key | Default | Extra          |<br>+-------------------+------------------+------+-----+---------+----------------+<br>| category_image_id | int(10) unsigned | NO   | PRI | NULL    | auto_increment |<br>| category_fid      | int(10) unsigned | YES  | MUL | NULL    |                |<br>| category_pic1     | mediumblob       | YES  |     | NULL    |                |<br>+-------------------+------------------+------+-----+---------+----------------+</pre><h3>2. Spring Boot Controller</h3><p>Here is the Spring Boot controller to fetch category data along with images:<br>Controller Code 🧑‍💻</p><pre>import org.json.JSONArray;<br>import org.json.JSONObject;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.MediaType;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestMethod;<br>import org.springframework.web.bind.annotation.RestController;<br>import java.sql.ResultSet;<br><br>@RestController<br>public class CategoryController {<br><br>    @Autowired<br>    private DatabaseConnection dbCon; // Custom database connection utility<br><br>    @RequestMapping(value = &quot;/category&quot;, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)<br>    public ResponseEntity&lt;Object&gt; selectCategoryQuery() {<br>        try {<br>            String query = &quot;SELECT c.category_id, c.category, c.description, ci.category_pic1 &quot; +<br>                           &quot;FROM category c &quot; +<br>                           &quot;LEFT JOIN category_image ci ON c.category_id = ci.category_fid &quot; +<br>                           &quot;WHERE c.category_status=&#39;active&#39; AND c.for_app=true&quot;;<br><br>            ResultSet rs = dbCon.getSql(query);<br>            JSONArray json = convertResultSetToJson(rs);<br>            return new ResponseEntity&lt;&gt;(json.toString(), HttpStatus.OK);<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>            return new ResponseEntity&lt;&gt;(&quot;Error fetching data&quot;, HttpStatus.INTERNAL_SERVER_ERROR);<br>        }<br>    }<br><br>    private JSONArray convertResultSetToJson(ResultSet rs) {<br>        JSONArray json = new JSONArray();<br>        try {<br>            java.sql.ResultSetMetaData rsmd = rs.getMetaData();<br>            while (rs.next()) {<br>                int numColumns = rsmd.getColumnCount();<br>                JSONObject obj = new JSONObject();<br>                for (int i = 1; i &lt;= numColumns; i++) {<br>                    String columnName = rsmd.getColumnName(i);<br>                    obj.put(columnName, rs.getObject(columnName));<br>                }<br>                json.put(obj);<br>            }<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>        return json;<br>    }<br>}<br></pre><h3>Flutter Implementation</h3><h3>1. Install Dependencies</h3><p>Add the http package to your pubspec.yaml for API integration:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  http: ^0.15.0 # Ensure you have the latest compatible version</pre><h3>2. Create the Widget</h3><p>Here is the complete code for a Flutter widget that fetches and displays categories and their images:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br><br>class CategoryList extends StatefulWidget {<br>  const CategoryList({Key? key}) : super(key: key);<br><br>  @override<br>  _CategoryListState createState() =&gt; _CategoryListState();<br>}<br><br>class _CategoryListState extends State&lt;CategoryList&gt; {<br>  List&lt;dynamic&gt; categories = [];<br>  bool isLoading = true;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    fetchCategories();<br>  }<br><br>  Future&lt;void&gt; fetchCategories() async {<br>    final url = Uri.parse(&#39;http://your-server-endpoint/category&#39;); // Replace with your API endpoint<br>    try {<br>      final response = await http.get(url);<br>      if (response.statusCode == 200) {<br>        setState(() {<br>          categories = jsonDecode(response.body);<br>          isLoading = false;<br>        });<br>      } else {<br>        throw Exception(&#39;Failed to load categories&#39;);<br>      }<br>    } catch (e) {<br>      setState(() {<br>        isLoading = false;<br>      });<br>      debugPrint(&#39;Error: $e&#39;);<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Categories&#39;),<br>      ),<br>      body: isLoading<br>          ? const Center(child: CircularProgressIndicator())<br>          : categories.isEmpty<br>              ? const Center(child: Text(&#39;No categories found&#39;))<br>              : ListView.builder(<br>                  itemCount: categories.length,<br>                  itemBuilder: (context, index) {<br>                    final category = categories[index];<br>                    return Card(<br>                      elevation: 4,<br>                      margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),<br>                      child: ListTile(<br>                        leading: category[&#39;category_pic1&#39;] != null<br>                            ? Image.memory(<br>                                base64Decode(category[&#39;category_pic1&#39;]),<br>                                width: 50,<br>                                height: 50,<br>                                fit: BoxFit.cover,<br>                              )<br>                            : const Icon(Icons.category),<br>                        title: Text(category[&#39;category&#39;] ?? &#39;Unknown Category&#39;),<br>                        subtitle: Text(category[&#39;description&#39;] ?? &#39;No description available&#39;),<br>                      ),<br>                    );<br>                  },<br>                ),<br>    );<br>  }<br>}</pre><h3>Key Implementation Details</h3><p><strong>Image Decoding:</strong> The category_pic1 field is Base64-encoded. We use base64Decode to convert it into a binary format and display it using Image.memory.</p><p><strong>convertResultSetToJson Method:</strong> The Spring Boot utility method transforms the ResultSet from SQL queries into a JSON array. Each row is represented as a JSON object, making it easier for the Flutter app to parse and utilize the data.</p><p><strong>Base64 Decoding:</strong> In the Flutter widget, the category_pic1 field contains a Base64-encoded image string. We use the base64Decode function to convert the string into binary data.</p><p><strong>Image.memory:</strong> The binary data is passed to Image.memory to render the image within the Flutter app. This approach ensures the app displays images directly from the database without storing them locally.</p><h3>Conclusion</h3><p>By combining the convertResultSetToJson method in Spring Boot with Flutter&#39;s Image.memory widget, we achieve seamless integration between the backend and frontend. The backend provides dynamic data and Base64-encoded images, while the frontend decodes and renders them efficiently.</p><p>With this solution, you can extend the functionality to include additional features, such as caching images, handling errors gracefully, or improving performance for large datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKknwQPkZvKE4qgU5OxUhA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=110b309685f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Data Handling with Future and Await in Flutter]]></title>
            <link>https://medium.com/@navinprince.thegr8gossiper/asynchronous-data-handling-with-future-and-await-in-flutter-88bee07018c3?source=rss-83f4b84c400f------2</link>
            <guid isPermaLink="false">https://medium.com/p/88bee07018c3</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[await]]></category>
            <dc:creator><![CDATA[Navin Prince]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 15:03:35 GMT</pubDate>
            <atom:updated>2024-11-08T15:03:35.004Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s create a simple example in Flutter using Future and await. We&#39;ll simulate fetching data from a server with a delay and display it in the UI.</p><ol><li><strong>Define an async function that simulates fetching data</strong>:</li></ol><pre>Future&lt;String&gt; fetchData() async {<br>  await Future.delayed(Duration(seconds: 2)); // Simulate a delay<br>  return &#39;Hello from the Future!&#39;;<br>}</pre><p>2. <strong>Use </strong>FutureBuilder<strong> to call the async function and display the result</strong>:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Scaffold(<br>        appBar: AppBar(title: Text(&#39;Future and Await Example&#39;)),<br>        body: Center(child: DataLoader()),<br>      ),<br>    );<br>  }<br>}<br><br>class DataLoader extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return FutureBuilder&lt;String&gt;(<br>      future: fetchData(), // Call the async function<br>      builder: (context, snapshot) {<br>        if (snapshot.connectionState == ConnectionState.waiting) {<br>          return CircularProgressIndicator(); // Show a loading indicator<br>        } else if (snapshot.hasError) {<br>          return Text(&#39;Error: ${snapshot.error}&#39;); // Handle errors<br>        } else {<br>          return Text(snapshot.data ?? &#39;No Data&#39;); // Display the fetched data<br>        }<br>      },<br>    );<br>  }<br><br>  // Simulate fetching data asynchronously<br>  Future&lt;String&gt; fetchData() async {<br>    await Future.delayed(Duration(seconds: 2)); // Simulate a delay<br>    return &#39;Hello from the Future!&#39;;<br>  }<br>}</pre><p>In this example:</p><ul><li>fetchData is an asynchronous function that simulates a 2-second delay before returning a string.</li><li>FutureBuilder is used in the DataLoader widget to handle the Future returned by fetchData.</li><li>While waiting for the Future to complete, a CircularProgressIndicator is displayed.</li><li>Once the Future completes, the result is shown in a Text widget.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*en0FEie_hZx68eV_ukoxEQ.jpeg" /></figure><p>This is a simple way to use Future and await in Flutter to handle asynchronous operations and update the UI accordingly. Try it out and see how it works!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88bee07018c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>