<?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 Ashutosh Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Agarwal on Medium]]></description>
        <link>https://medium.com/@ashutoshagarwal2014?source=rss-d6af75554eeb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cFpOgHg2Uz5cFY7Z2RTgAw.jpeg</url>
            <title>Stories by Ashutosh Agarwal on Medium</title>
            <link>https://medium.com/@ashutoshagarwal2014?source=rss-d6af75554eeb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:53:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutoshagarwal2014/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[New Official SKILLS for Dart and Flutter]]></title>
            <link>https://ashutoshagarwal2014.medium.com/new-official-skills-for-dart-and-flutter-60537a7914a2?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/60537a7914a2</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[skills]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Mon, 11 May 2026 03:29:28 GMT</pubDate>
            <atom:updated>2026-05-11T03:29:28.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Joins the AI Agent Era with Official Skills Repositories</h3><p>The AI-assisted development race is evolving fast — and now the Dart and Flutter teams are officially joining it.</p><p>A major new step has quietly appeared from the teams behind Dart and Flutter: <strong>official “Skills” repositories designed for AI agents and coding assistants.</strong></p><p>This signals something much bigger than just another GitHub repo.</p><p>Developers are moving from:</p><p><strong>autocomplete → AI copilots → autonomous coding agents.</strong></p><p>And “Skills” are becoming the new way to teach AI systems how to work with frameworks professionally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7aSL0BOH_ql6dSetthnpA.png" /></figure><h3>What Are Agent Skills?</h3><p>In the AI tooling ecosystem, <strong>Skills</strong> are structured capabilities that help AI agents: <strong>understand frameworks, follow best practices, generate production-ready code, execute workflows correctly, and reduce hallucinations.</strong></p><p>Instead of giving vague prompts, developers can provide reusable “skills” that encode: <strong>architecture patterns, conventions, commands, workflows, templates, debugging flows, and framework-specific knowledge.</strong></p><p>Think of them as:</p><blockquote><em>“Reusable expertise modules for AI coding agents.”</em></blockquote><p>This trend is already growing rapidly across: <strong>AI IDEs, autonomous agents, developer tooling, and workflow automation systems.</strong></p><p>Now the Flutter ecosystem officially enters that space.</p><h3>The Two New Official Repositories</h3><p>Google teams recently published:</p><ul><li><a href="https://github.com/dart-lang/skills?utm_source=chatgpt.com">dart-lang/skills repository</a></li><li><a href="https://github.com/flutter/skills?utm_source=chatgpt.com">flutter/skills repository</a></li></ul><p>These repositories provide structured knowledge and workflows specifically designed for AI-assisted development.</p><p>This is important because:</p><ul><li>AI tools work best with framework-specific context.</li><li>Generic coding agents often struggle with project conventions.</li><li>Official framework-backed skills dramatically improve reliability.</li></ul><h3>Why This Matters for Flutter Developers</h3><p>For years, Flutter developers relied on: <strong>prompts, snippets, Stack Overflow, boilerplates, and trial-and-error with AI tools.</strong></p><p>But official skills can now help agents:</p><ul><li><strong>Generate better Flutter architecture,</strong></li><li><strong>Follow Dart idioms correctly,</strong></li><li><strong>Understand widget structures,</strong></li><li><strong>Apply state management patterns,</strong></li><li><strong>Reduce invalid code generation.</strong></li></ul><p>This could significantly improve workflows in tools like:</p><ul><li>GitHub Copilot</li><li>Cursor</li><li>Claude</li><li>Windsurf</li><li>Agentic IDE systems,</li><li>Future autonomous development platforms.</li></ul><h3>Bigger Than Flutter</h3><p>This is part of a larger industry transition.</p><p>Frameworks are starting to realize:</p><blockquote><em>If AI agents are writing code, they need official guidance.</em></blockquote><p>We’re entering an era where:<strong><em> documentation is no longer enough, APIs are no longer enough, examples are no longer enough.</em></strong></p><p>Frameworks now need: <strong><em>AI-native tooling, structured instructions, machine-readable workflows, and agent-compatible development standards.</em></strong></p><p>Flutter adopting this early is a smart move.</p><h3>What This Could Enable Next</h3><p>Official Skills may eventually power: <strong><em>automatic feature generation, architecture-aware agents, intelligent refactoring, migration assistants, test-generation workflows, CI/CD automation, and fully autonomous Flutter development pipelines.</em></strong></p><p>The most interesting part:</p><blockquote><em>This is probably just the beginning.</em></blockquote><h3>Final Thoughts</h3><p>The launch of official Skills repositories by the Dart and Flutter teams is a strong signal about where software development is heading.</p><p>AI coding assistants are no longer experimental side tools.</p><p>They are becoming part of the development stack itself.</p><p>And frameworks that provide official AI guidance early may gain a massive advantage in: <strong><em>developer productivity, ecosystem adoption, and long-term AI compatibility.</em></strong></p><p>Flutter is now officially preparing for the agentic development era.</p><p>The future of software engineering may not just be:</p><blockquote><em>“writing code”</em></blockquote><p>but:</p><blockquote><em>“teaching agents how to build software correctly.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60537a7914a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parse JSON in the Background in Flutter — No More UI Jank!]]></title>
            <link>https://ashutoshagarwal2014.medium.com/parse-json-in-the-background-in-flutter-no-more-ui-jank-e73688333678?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e73688333678</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[jank]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutterjson]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 02:00:40 GMT</pubDate>
            <atom:updated>2025-12-22T02:12:40.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parse JSON in the Background in Flutter — No More UI Jank!</h3><p>Flutter apps are fast, smooth, and beautifully animated. But if you’ve ever tried parsing a large JSON file directly on the main thread, you’ve probably seen your app stutter, freeze, or completely lock up for a moment.</p><p>That little freeze is called <strong>jank</strong> — and it breaks the smooth user experience we work so hard to build.</p><p>In this article, I’ll walk you through how to parse JSON <strong>in the background</strong> using isolates in Flutter. You’ll learn why isolates matter, how to use compute(), and you’ll walk away with a complete example you can paste right into your project.</p><h3>Why Parse JSON in the Background?</h3><p>By default, Dart runs all code on a single thread. Most of the time, that’s great — Flutter stays simple and responsive. But if you perform expensive tasks like:</p><ul><li>parsing thousands of JSON objects</li><li>processing large files</li><li>performing heavy CPU calculations</li></ul><p>…your UI will freeze.</p><p>If a frame takes longer than <strong>16ms</strong>, animations begin to stutter. A JSON document with a few thousand items can easily take longer than that.</p><p>To fix this issue, Flutter lets you run expensive computations in a separate <strong>isolate</strong>. Think of isolates as mini background workers that don’t block the UI.</p><h3>What We’re Building</h3><p>We’re going to:</p><ol><li>Fetch a list of photo objects from the network</li><li>Parse a large JSON response</li><li>Convert it into Dart classes</li><li>Move parsing to a background isolate using compute()</li></ol><p>This approach keeps the UI buttery smooth — even for slow devices.</p><h3>Step 1 — Add the HTTP package</h3><p>We need the http package to make the network request.</p><p>Add it from the terminal:</p><pre>flutter pub add http</pre><h3>Step 2 — Fetch JSON from the Internet</h3><p>We’ll download 5000 photo items from JSONPlaceholder:</p><pre>Future&lt;http.Response&gt; fetchPhotos(http.Client client) async {<br>  return client.get(Uri.parse(&#39;https://jsonplaceholder.typicode.com/photos&#39;));<br>}</pre><blockquote><em>Notice how we pass </em><em>http.Client into the function?<br>This makes testing easier and avoids global state.</em></blockquote><h3>Step 3 — Create a Model Class</h3><p>We define a Photo class to map JSON data into strongly-typed Dart objects:</p><pre>class Photo {<br>  final int albumId;<br>  final int id;<br>  final String title;<br>  final String url;<br>  final String thumbnailUrl;<br>  <br>  const Photo({<br>    required this.albumId,<br>    required this.id,<br>    required this.title,<br>    required this.url,<br>    required this.thumbnailUrl,<br>  });<br>  factory Photo.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return Photo(<br>      albumId: json[&#39;albumId&#39;] as int,<br>      id: json[&#39;id&#39;] as int,<br>      title: json[&#39;title&#39;] as String,<br>      url: json[&#39;url&#39;] as String,<br>      thumbnailUrl: json[&#39;thumbnailUrl&#39;] as String,<br>    );<br>  }<br>}</pre><h3>Step 4 — Parse JSON into Dart Objects</h3><p>First, parse synchronously:</p><pre>List&lt;Photo&gt; parsePhotos(String responseBody) {<br>  final parsed = (jsonDecode(responseBody) as List)<br>      .cast&lt;Map&lt;String, dynamic&gt;&gt;();<br>  return parsed.map&lt;Photo&gt;(Photo.fromJson).toList();<br>}</pre><p>Then update the fetch function:</p><pre>Future&lt;List&lt;Photo&gt;&gt; fetchPhotos(http.Client client) async {<br>  final response = await client.get(<br>    Uri.parse(&#39;https://jsonplaceholder.typicode.com/photos&#39;),<br>  );<br>  return parsePhotos(response.body);<br>}</pre><p>If you run this now on a slow device, you may see UI freezes — especially when scrolling immediately after fetching data.</p><h3>Step 5 — Move JSON Parsing to an Isolate</h3><p>Flutter offers the compute() function to help run heavy tasks off the main thread:</p><pre>return compute(parsePhotos, response.body);</pre><p>Here’s the updated fetching function:</p><pre>Future&lt;List&lt;Photo&gt;&gt; fetchPhotos(http.Client client) async {<br>  final response = await client.get(<br>    Uri.parse(&#39;https://jsonplaceholder.typicode.com/photos&#39;),<br>  );<br>  // parse in the background<br>  return compute(parsePhotos, response.body);<br>}</pre><p>Now parsing runs on a background isolate — and the UI stays perfectly smooth.</p><h3>Isolate Limitations to Know</h3><p>Isolates cannot share complex objects directly. Data sent between isolates must be:</p><ul><li>Strings</li><li>numbers</li><li>booleans</li><li>lists</li><li>maps</li><li>simple objects</li></ul><p>You <strong>cannot</strong> pass:</p><ul><li>Futures</li><li>http.Response</li><li>open file handles</li></ul><p>This is why we send only the <strong>response body string</strong> through compute().</p><h3>Full Working Flutter Example</h3><p>Here’s the complete demo app that shows thumbnails in a grid, backed by isolate-powered parsing:</p><p>👉 Scroll up to the code in the original snippet; the example is plug-and-play.</p><h3>Alternatives to Compute()</h3><p>If you need more advanced multi-threading, check out:</p><ul><li>worker_manager</li><li>workmanager</li><li>custom isolates</li></ul><p>These are great options when:</p><ul><li>the app runs background tasks while closed</li><li>you need isolate pools</li><li>tasks run repeatedly</li></ul><h3>Final Thoughts</h3><p>Parsing JSON on the main thread can introduce UI jank — even in powerful devices. Flutter gives us a clean way to avoid this through isolates using the compute() function.</p><p>With one line change, we moved from laggy parsing to smooth animations:</p><pre>return compute(parsePhotos, response.body);</pre><p>Next time you face heavy workloads, don’t block the UI. Background isolates exist for this exact reason.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e73688333678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving ANRs In Flutter App After Flutter’s “Great Thread Merge”]]></title>
            <link>https://ashutoshagarwal2014.medium.com/solving-anrs-in-flutter-app-after-flutters-great-thread-merge-6e7101c52b5f?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e7101c52b5f</guid>
            <category><![CDATA[google-play-store]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 20:31:36 GMT</pubDate>
            <atom:updated>2025-10-24T20:31:36.295Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Published: October 2025 — by Ashutosh Agarwal</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxbVo8oCpj5v06vvjEBhsQ.png" /></figure><h3>Introduction</h3><p>If you recently upgraded your Flutter project to <strong>Flutter 3.29+</strong> and suddenly started seeing <strong>ANRs (Application Not Responding errors)</strong> on Android, you’re not alone.</p><p>Many developers have been caught off guard by Flutter’s major architectural change — the <strong>“Great Thread Merge”</strong> — which fundamentally alters how Flutter manages threads between Dart and the platform (Android/iOS/macOS) layers.</p><p>Let’s unpack <strong>why this change introduces new ANR risks</strong>, what’s really going on under the hood, and most importantly — <strong>how to fix it safely and permanently.</strong></p><h3>What Changed: The Great Thread Merge Explained</h3><p>Before Flutter 3.29, the engine had a <strong>multi-threaded architecture</strong>:</p><ul><li><strong>UI Thread</strong> → Ran Dart code and built widgets.</li><li><strong>Platform Thread</strong> → Executed native Android/iOS code (via JNI).</li><li><strong>Raster Thread</strong> → Rendered frames (GPU work).</li></ul><p>This separation meant that when Dart called a native API through a <strong>platform channel</strong>, the call was asynchronous — blocking operations on the native side couldn’t freeze the UI thread.</p><h3>After the Merge</h3><p>Starting from Flutter <strong>3.29 (Android/iOS)</strong> and <strong>3.35 (Windows/macOS)</strong>, Flutter <strong>merged the UI and platform threads</strong> into one.</p><p>That means:</p><blockquote><em>Dart + native platform code now run on the </em><strong><em>same thread</em></strong><em>.</em></blockquote><p>It simplifies the architecture, but it also means <strong>any heavy native operation</strong> can now directly block your app’s UI — leading to <strong>ANRs</strong>, frame drops, or input freezes.</p><h3>Why ANRs Appear After the Merge</h3><p>When the UI and platform threads merge, these previously safe patterns become risky:</p><pre>// BAD: This runs on the merged main thread now!<br>Thread.sleep(100) <br>val bitmap = BitmapFactory.decodeFile(&quot;/storage/pictures/large.png&quot;)</pre><p>or in Dart:</p><pre>// Still runs on main thread if the native call blocks<br>await platform.invokeMethod(&#39;loadLargeFile&#39;);</pre><p>Before, this would slow the platform thread — not your UI.<br> Now, it <strong>freezes the whole app</strong>, and Android’s watchdog process will trigger an <strong>ANR</strong> if it lasts more than 5 seconds.</p><h3>Common Causes of Post-Merge ANRs</h3><p>Source Why It’s Problematic Now <strong>Blocking I/O in native code</strong> Disk or network reads on the merged main thread freeze the app <strong>Heavy plugin initialization</strong> Plugins doing sync work in configureFlutterEngine now block UI <strong>Synchronous JNI or reflection calls</strong> Previously async, now fully blocking <strong>Unoptimized third-party plugins</strong> Many haven’t been updated for the new model yet <strong>Misuse of async/isolates in Dart</strong> Heavy Dart work not offloaded from main thread</p><h3>Solutions: Fixing or Avoiding ANRs</h3><h3>1. Temporarily Disable the Merge (Safe Debug Option)</h3><p>If you’re in production and need immediate stability, you can <strong>opt out</strong> of the thread merge on Android:</p><pre>&lt;!-- AndroidManifest.xml --&gt;<br>&lt;application<br>    android:name=&quot;${applicationName}&quot;<br>    android:label=&quot;MyApp&quot;<br>    android:icon=&quot;@mipmap/ic_launcher&quot;&gt;<br><br>&lt;meta-data<br>        android:name=&quot;io.flutter.embedding.android.DisableMergedPlatformUIThread&quot;<br>        android:value=&quot;true&quot; /&gt;<br>&lt;/application&gt;</pre><p>This restores the old threading model and can stop ANRs instantly — <br> but it’s <strong>a short-term fix</strong>, not a permanent solution.<br> This flag may be <strong>removed in future Flutter versions</strong>.</p><h3>2. Offload Heavy Work to Background Threads or Isolates</h3><p>If your plugin or Dart code performs any blocking work (file parsing, compression, network I/O), move it <strong>off the main thread</strong>.</p><h4>Dart example:</h4><pre>// Instead of doing heavy work on UI thread:<br>final data = processFileSync(path);<br><br>// ✅ Use compute() or an isolate:<br>final data = await compute(processFileSync, path);</pre><h3>3. Audit Your Plugins</h3><p>Check all your dependencies:</p><pre>flutter pub deps --style=compact</pre><p>Then, review plugins that use native code (android/src/, ios/Classes/).<br> If they do blocking I/O or bitmap decoding synchronously — they need an update.</p><p>You can often find “thread merge compatible” updates in newer versions or GitHub branches.</p><h3>4. Profile Performance</h3><p>Use Flutter DevTools → <strong>Performance tab</strong> or Android Studio’s <strong>CPU Profiler</strong> to find slow frames and thread blocking.</p><p>Look for:</p><ul><li>“Platform thread stalled for Xms”</li><li>“Skipped frames”</li><li>“Input dispatching timed out” in Logcat</li></ul><p>This will pinpoint exactly where your main thread freezes.</p><h3>5. Remove the Disable Flag Once Stable</h3><p>Once you’ve refactored heavy work and validated plugin updates, <strong>remove</strong> the opt-out flag to regain the benefits of the merged architecture:</p><ul><li>Lower startup latency</li><li>More direct native API access</li><li>Fewer async boundaries between Dart and platform code</li></ul><h3>Long-Term Impacts of the Thread Merge</h3><pre>| Impact                     | Description                                                     |<br>| -------------------------- | --------------------------------------------------------------- |<br>| Simpler architecture       | Unified main thread simplifies interop and improves consistency |<br>| Faster native calls        | Synchronous calls between Dart and platform reduce latency      |<br>| Less boilerplate           | Fewer platform channel round-trips                              |<br>| Higher ANR risk if careless| Heavy work now blocks UI thread                                 |<br>| Plugin updates required    | Outdated plugins may misbehave until adapted                    |</pre><h3>The Future</h3><p>Flutter’s Great Thread Merge is part of a bigger vision — <strong>unifying Dart and native runtimes</strong> for lower overhead and more predictable performance.</p><p>It’s a major leap forward, but it comes with responsibility: developers now need to treat the Flutter main thread the same way Android or iOS developers treat their UI thread — <strong>keep it light, fast, and non-blocking.</strong></p><h3>Final Thoughts</h3><p>If your app started freezing or hitting ANRs after upgrading Flutter:</p><ul><li>Don’t panic — it’s not a bug, it’s the new normal.</li><li>Use the &lt;meta-data&gt; opt-out for quick stability.</li><li>Then gradually migrate your code to fit the merged threading model.</li></ul><p>Once optimized, you’ll enjoy <strong>smoother interop</strong>, <strong>faster startup</strong>, and a <strong>cleaner architecture</strong>.</p><p>✍️ <em>Written by Ashutosh Agarwal</em><br> 💬 <em>Flutter Engineer | Performance Enthusiast | Always optimizing main threads</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e7101c52b5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Vibration Feedback in Flutter with vibration]]></title>
            <link>https://ashutoshagarwal2014.medium.com/adding-vibration-feedback-in-flutter-with-vibration-461e95b14768?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/461e95b14768</guid>
            <category><![CDATA[flutter-vibration]]></category>
            <category><![CDATA[vibration]]></category>
            <category><![CDATA[haptics]]></category>
            <category><![CDATA[haptic-feedback]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 23:21:12 GMT</pubDate>
            <atom:updated>2025-09-27T23:21:12.716Z</atom:updated>
            <content:encoded><![CDATA[<p>User experience is not only about what we <strong>see</strong> on the screen but also about what we <strong>feel</strong>. Haptic feedback (vibration) can make apps more engaging and intuitive. Luckily, Flutter provides great support for this through the <a href="https://pub.dev/packages/vibration">vibration</a> package.</p><p>In this article, we’ll explore how to set up and use the vibration plugin (version 3.1.4), which is <strong>Dart 3 compatible</strong> and works across Android, iOS, Web, and even OpenHarmony.</p><h3>🔧 Step 1: Install the package</h3><p>Add the following dependency in your pubspec.yaml:</p><pre>dependencies:<br>  vibration: ^3.1.4</pre><p>Run:</p><pre>flutter pub get</pre><h3>📥 Step 2: Import the package</h3><pre>import &#39;package:vibration/vibration.dart&#39;;</pre><h3>📱 Step 3: Using vibration in Flutter</h3><h3>1. Check if the device supports vibration</h3><pre>if (await Vibration.hasVibrator() ?? false) {<br>  Vibration.vibrate();<br>}</pre><p>This prevents errors on devices without vibration support.</p><h3>2. Simple vibration</h3><pre>Vibration.vibrate(); // default 500ms</pre><p>Or specify a custom duration:</p><pre>Vibration.vibrate(duration: 1000); // vibrate for 1 second</pre><h3>3. Vibration with amplitude (Android 8+)</h3><pre>if (await Vibration.hasAmplitudeControl() ?? false) {<br>  Vibration.vibrate(duration: 1000, amplitude: 128);<br>}</pre><h3>4. Vibration patterns</h3><pre>// Wait 500ms, vibrate 1s, wait 500ms, vibrate 2s<br>Vibration.vibrate(pattern: [500, 1000, 500, 2000]);</pre><p>With varying intensities:</p><pre>Vibration.vibrate(<br>  pattern: [500, 1000, 500, 2000],<br>  intensities: [64, 255],<br>);</pre><h3>5. Vibration presets</h3><p>The package comes with predefined vibration styles:</p><pre>Vibration.vibrate(preset: VibrationPreset.alarm);<br>Vibration.vibrate(preset: VibrationPreset.doubleBuzz);<br>Vibration.vibrate(preset: VibrationPreset.quickSuccessAlert);</pre><p>These are useful for common UX cases like notifications, success alerts, or warnings.</p><h3>6. Cancel ongoing vibration</h3><pre>Vibration.cancel();</pre><h3>⚙️ Android setup</h3><p>Make sure to add vibration permission in your AndroidManifest.xml:</p><pre>&lt;uses-permission android:name=&quot;android.permission.VIBRATE&quot;/&gt;</pre><h3>🚀 Full Example</h3><p>Here’s a quick example of a button that triggers vibration:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:vibration/vibration.dart&#39;;<br><br>class VibraButton extends StatelessWidget {<br>  const VibraButton({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;Vibration Example&quot;)),<br>      body: Center(<br>        child: ElevatedButton(<br>          onPressed: () async {<br>            if (await Vibration.hasVibrator() ?? false) {<br>              Vibration.vibrate(preset: VibrationPreset.doubleBuzz);<br>            }<br>          },<br>          child: const Text(&quot;Press Me&quot;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>🎯 Conclusion</h3><p>Adding vibration feedback in Flutter is straightforward with the vibration package. It allows you to:</p><ul><li>Vibrate with custom durations</li><li>Use patterns and intensities</li><li>Trigger built-in presets</li><li>Check device support before vibrating</li></ul><p>This small enhancement can significantly improve the <strong>user experience</strong> by making interactions more natural and responsive.</p><p>👉 Next time you build a button, notification, or alert in your Flutter app, try adding a little buzz!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=461e95b14768" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlling Font Scaling in Flutter: Stop Your App Text from Growing with Device Settings]]></title>
            <link>https://ashutoshagarwal2014.medium.com/controlling-font-scaling-in-flutter-stop-your-app-text-from-growing-with-device-settings-a2e596bce487?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e596bce487</guid>
            <category><![CDATA[flutter-text-scaling]]></category>
            <category><![CDATA[flutter-fonts]]></category>
            <category><![CDATA[flutter-text]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[fonts]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 12:12:06 GMT</pubDate>
            <atom:updated>2025-09-26T12:12:06.527Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever noticed that your Flutter app’s text suddenly looks <strong>too big</strong> or <strong>too small</strong> when the user changes their device’s font size? That’s because Flutter, by default, respects the device’s <strong>system font scaling</strong>. While this is great for accessibility, it can sometimes break your UI design.</p><p>In this article, we’ll look at <strong>why this happens</strong> and explore <strong>different strategies</strong> to control or limit text scaling in Flutter.</p><h3>🔍 Why Does Font Scaling Happen?</h3><p>Flutter reads the device’s accessibility settings and applies a multiplier called textScaleFactor. This multiplier affects all text in your app. For example:</p><ul><li>If the user sets their phone’s font size to <strong>Large</strong>, textScaleFactor might be 1.5.</li><li>If they set it to <strong>Small</strong>, textScaleFactor might be 0.8.</li></ul><p>This means:</p><pre>Text(&quot;Hello World&quot;);</pre><p>will render at a different size depending on the system settings.</p><h3>Option 1: Disable Scaling Globally</h3><p>If you want your app’s text to <strong>always look the same</strong>, you can override the scaling globally in your MaterialApp.</p><pre>MaterialApp(<br>  builder: (context, child) {<br>    return MediaQuery(<br>      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),<br>      child: child!,<br>    );<br>  },<br>  home: MyHomePage(),<br>);</pre><p>✅ This forces all text to ignore device scaling.</p><p>⚠️ But be careful: this removes accessibility support, which might not be ideal if your app is used by people with vision impairments.</p><h3>Option 2: Disable Scaling for Specific Text Widgets</h3><p>Sometimes you only want <strong>certain widgets</strong> to ignore scaling (like titles or buttons).</p><pre>Text(<br>  &quot;Hello World&quot;,<br>  textScaler: TextScaler.linear(1.0),<br>);</pre><p>This way, only the specified text stays fixed while the rest of the app respects system scaling.</p><h3>🛠️ Option 3: Limit (Clamp) Font Scaling</h3><p>What if you want to allow some scaling, but not too much? You can <strong>clamp</strong> the scale factor:</p><pre>MediaQuery(<br>  data: MediaQuery.of(context).copyWith(<br>    textScaleFactor: MediaQuery.of(context).textScaleFactor.clamp(1.0, 1.2),<br>  ),<br>  child: child,<br>);</pre><p>Here, your text will:</p><ul><li>Scale normally between <strong>100% and 120%</strong>.</li><li>Ignore extreme settings like <strong>Extra Large</strong> or <strong>Extra Small</strong>.</li></ul><p>This keeps your app layout safe while still being somewhat accessible.</p><h3>✅ Best Practices</h3><ul><li>Use <strong>Option 1 (disable globally)</strong> if your app requires <strong>pixel-perfect UI</strong> (e.g., design-heavy apps).</li><li>Use <strong>Option 2 (disable selectively)</strong> if only certain widgets must remain fixed.</li><li>Use <strong>Option 3 (clamp scaling)</strong> for the best balance between <strong>UI safety</strong> and <strong>accessibility</strong>.</li></ul><h3>🚀 Final Thoughts</h3><p>Controlling font scaling in Flutter is easy once you know how textScaleFactor works. Whether you choose to disable it completely, control it per widget, or clamp it globally depends on your app’s <strong>design requirements</strong> and <strong>user base</strong>.</p><p>The key is finding the right balance between <strong>beautiful UI</strong> and <strong>accessibility</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e596bce487" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Environment & Version Management for Mobile Apps: Dev, Staging, and Production Best Practices]]></title>
            <link>https://ashutoshagarwal2014.medium.com/api-environment-version-management-for-mobile-apps-dev-staging-and-production-best-practices-474f37cc060d?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/474f37cc060d</guid>
            <category><![CDATA[mobile-app-deployment]]></category>
            <category><![CDATA[api-environment]]></category>
            <category><![CDATA[app-environment]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[version-management]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 20:48:18 GMT</pubDate>
            <atom:updated>2025-08-31T20:48:18.860Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to manage API environments and versioning in mobile apps. Discover best practices for Android build flavors, iOS schemes, and deploying safely to Play Store and App Store.</p><h3>Introduction</h3><p>Building mobile apps often requires connecting to a backend API. However, managing <strong>different API environments</strong> (development, staging, production) while ensuring <strong>smooth API versioning</strong> can be challenging. Deploying apps to the Play Store and App Store without careful planning can lead to pointing your production app to a development API or breaking older app versions.</p><p>In this article, we’ll cover best practices for <strong>API environment configuration</strong>, <strong>versioning strategies</strong>, and <strong>how to handle them in Android and iOS apps</strong>.</p><h3>Why API Environment Management Matters</h3><p>Mobile developers typically deal with multiple environments:</p><ul><li><strong>Development</strong> — for building and testing features.</li><li><strong>Staging</strong> — for QA and internal testing.</li><li><strong>Production</strong> — the live app used by real users.</li></ul><p>Using separate APIs ensures:</p><ul><li>Safe testing without affecting real users.</li><li>Easier bug tracking and debugging.</li><li>Clear separation between test and live data.</li></ul><h3>Android: Using Build Flavors</h3><p>Android supports <strong>build flavors</strong> to manage different API endpoints. Example:</p><pre>android {<br>    buildTypes {<br>        debug {<br>            buildConfigField &quot;String&quot;, &quot;BASE_URL&quot;, &quot;\&quot;https://dev-api.example.com/\&quot;&quot;<br>        }<br>        release {<br>            buildConfigField &quot;String&quot;, &quot;BASE_URL&quot;, &quot;\&quot;https://api.example.com/\&quot;&quot;<br>        }<br>    }<br>    productFlavors {<br>        dev { dimension &quot;environment&quot; }<br>        prod { dimension &quot;environment&quot; }<br>    }<br>}</pre><p>Access in Kotlin:</p><pre>val baseUrl = BuildConfig.BASE_URL</pre><h3>iOS: Schemes and Configurations</h3><p>iOS developers can use <strong>Xcode schemes</strong> with .xcconfig files:</p><p><strong>Dev.xcconfig</strong></p><pre>BASE_URL = https://dev-api.example.com/</pre><p><strong>Prod.xcconfig</strong></p><pre>BASE_URL = https://api.example.com/</pre><p>Access in Swift:</p><pre>let baseUrl = Bundle.main.object(forInfoDictionaryKey: &quot;BASE_URL&quot;) as? String</pre><h3>API Versioning: URL vs Header</h3><p>As APIs evolve, <strong>versioning</strong> ensures backward compatibility.</p><h3>1. URL Path Versioning (Most Common)</h3><pre>https://api.example.com/v1/users<br>https://api.example.com/v2/users</pre><h3>2. Header-Based Versioning</h3><pre>GET /users<br>X-API-Version: 2</pre><p><strong>Tip:</strong> Use <strong>URL path versioning</strong> for public APIs and <strong>headers</strong> for internal/enterprise APIs.</p><h3>Combining Environment and Version Management</h3><p>You can combine <strong>environment switching</strong> with <strong>API versioning</strong>:</p><p><strong>Dev Environment, v1 API</strong></p><pre>https://dev-api.example.com/users<br>X-API-Version: 1</pre><p><strong>Prod Environment, v2 API</strong></p><pre>https://api.example.com/users<br>X-API-Version: 2</pre><h3>CI/CD Integration</h3><p>For Play Store and App Store releases:</p><ul><li><strong>Dev/staging builds</strong> → distribute internally (Firebase, TestFlight).</li><li><strong>Prod builds</strong> → uploaded to Play Store / App Store with production API only.</li></ul><p>CI/CD pipelines can automatically inject API endpoints and version headers based on branch:</p><ul><li>develop → dev API</li><li>main → prod API</li></ul><h3>Best Practices</h3><ol><li><strong>Always version your API</strong> to maintain backward compatibility.</li><li><strong>Use build flavors/schemes</strong> for environment separation.</li><li><strong>Do not hardcode secrets</strong>; use environment variables in CI/CD.</li><li><strong>Keep production API endpoints safe</strong> in release builds.</li><li><strong>Consider optional runtime switching</strong> for QA/internal builds only.</li></ol><h3>Conclusion</h3><p>Managing API environments and versions effectively is crucial for building reliable mobile applications. By using <strong>build flavors, Xcode schemes, and versioning strategies</strong>, you can safely test, deploy, and evolve your mobile applications without breaking user experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=474f37cc060d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Gradient Text: Create a Reusable Widget with ShaderMask]]></title>
            <link>https://ashutoshagarwal2014.medium.com/flutter-gradient-text-create-a-reusable-widget-with-shadermask-2b8383b342c3?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b8383b342c3</guid>
            <category><![CDATA[flutter-gradient]]></category>
            <category><![CDATA[colorful-text]]></category>
            <category><![CDATA[gradient-text]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 02:54:33 GMT</pubDate>
            <atom:updated>2025-08-30T06:28:50.153Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Learn how to add gradient text in Flutter using ShaderMask. Build a reusable </em><em>GradientText widget and make your UI shine with colorful effects.</em></blockquote><h3>Introduction</h3><p>If you’ve ever tried to add gradient text in Flutter, you’ll notice something quickly: the Text widget doesn’t support gradients out of the box. By default, you can only assign a single one color through the TextStyle.</p><p>But what if you want to create beautiful titles, headings, or labels with a gradient effect?</p><p>In this tutorial, we’ll build a <strong>reusable </strong><strong>GradientText widget in Flutter</strong> using ShaderMask. This approach makes it simple to drop gradient text anywhere in your app with just one line of code.</p><p>By the end, you’ll know how to:</p><ul><li>Apply gradients to text in Flutter.</li><li>Support both <strong>linear and radial gradients</strong>.</li><li>Extend it later for <strong>animated gradient text</strong>.</li></ul><h3>❌ Why Flutter Doesn’t Support Gradient Text by Default</h3><p>The Text widget’s style system is designed around a single Color. Gradients are more complex because they require a shader — basically, a function that paints pixels dynamically.</p><p>That’s why we need to wrap our text with either:</p><ol><li><strong>ShaderMask</strong> – applies a gradient shader to any widget, including Text.</li><li><strong>Paint with shader in </strong><strong>TextStyle.foreground</strong> – a more direct way for text-only gradients.</li></ol><p>In this article, we’ll use ShaderMask because it’s flexible, reusable, and easy to extend.</p><h3>Building the GradientText Widget</h3><p>Here’s the final reusable GradientText widget implementation:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class GradientText extends StatelessWidget {<br>  final String text;<br>  final TextAlign? textAlign;<br>  final TextStyle? style;<br>  final double? size;<br>  final List&lt;Color&gt;? colors;<br>  final List&lt;double&gt;? stops;<br><br>  const GradientText(<br>    this.text, {<br>    super.key,<br>    this.textAlign,<br>    this.style,<br>    this.size,<br>    this.colors,<br>    this.stops,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ShaderMask(<br>      shaderCallback:<br>          (bounds) =&gt; LinearGradient(<br>            colors:<br>                colors ??<br>                [<br>                  Color(0xffFFA433),<br>                  Color(0xffCB5003),<br>                  Color(0xff2C0C5F),<br>                  Color(0xff2C0C5F),<br>                ],<br>            stops: stops ?? [0, 0.38, 0.76, 1],<br>            begin: Alignment.centerLeft,<br>            end: Alignment.centerRight,<br>          ).createShader(Rect.fromLTWH(0, 0, bounds.width, bounds.height)),<br>      child: Text(<br>        text,<br>        textAlign: textAlign,<br>        style:<br>            style ??<br>            TextStyle(<br>              fontSize: size ?? 18,<br>              height: 1,<br>              fontWeight: FontWeight.w600,<br>              color: Colors.white,<br>            ),<br>      ),<br>    );<br>  }<br>}</pre><h3>How It Works</h3><ul><li><strong>ShaderMask</strong>: Wraps the Text widget and applies a gradient shader.</li><li><strong>createShader</strong>: Defines how the gradient fills the widget’s bounds.</li><li><strong>Base white color</strong>: The text must be white to properly reveal the gradient.</li></ul><p>This widget is also flexible: you can pass your own gradient or just provide a list of colors.</p><h3>Using GradientText in Your App</h3><pre>GradientText(&#39;We are coming soon.&#39;);</pre><p>This produces a smooth linear gradient across the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*WM1QIFPqF7zZzvA4cXzo4w.png" /></figure><h3>✨ Bonus: Animated Gradient Text in Flutter</h3><p>Static gradients are nice, but moving gradients are even better. You can animate your gradient stops or the begin/end alignment to create effects like shimmer.</p><p>A quick starting point:</p><pre>class AnimatedGradientText extends StatefulWidget {<br>  final String text;<br>  const AnimatedGradientText(this.text, {super.key});<br>  @override<br>  State&lt;AnimatedGradientText&gt; createState() =&gt; _AnimatedGradientTextState();<br>}<br>class _AnimatedGradientTextState extends State&lt;AnimatedGradientText&gt;<br>    with SingleTickerProviderStateMixin {<br>  late AnimationController _controller;<br>  @override<br>  void initState() {<br>    super.initState();<br>    _controller =<br>        AnimationController(vsync: this, duration: Duration(seconds: 3))<br>          ..repeat();<br>  }<br>  @override<br>  void dispose() {<br>    _controller.dispose();<br>    super.dispose();<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedBuilder(<br>      animation: _controller,<br>      builder: (context, child) {<br>        return GradientText(<br>          widget.text,<br>          gradient: LinearGradient(<br>            colors: [Colors.blue, Colors.purple, Colors.red],<br>            begin: Alignment(-1 + _controller.value * 2, 0),<br>            end: Alignment(1 + _controller.value * 2, 0),<br>          ),<br>          style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>👉 This creates a looping, sliding gradient effect across the text. Perfect for headers, banners, or splash screens.</p><h3>📌 Final Thoughts</h3><p>Adding gradient text in Flutter might not be built-in, but withShaderMask, it becomes both simple and powerful. Wrapping it into a reusable GradientText widget makes your UI code clean, reusable, and flexible.</p><p>Whether you’re building a flashy splash screen, stylish headings, or eye-catching call-to-action labels, this widget is a must-have in your Flutter toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b8383b342c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Flutter’s DateTime.now() vs NTP.now(): When Device Time Isn’t Good Enough]]></title>
            <link>https://ashutoshagarwal2014.medium.com/%EF%B8%8F-flutters-datetime-now-vs-ntp-now-when-device-time-isn-t-good-enough-26cbf89ccb7f?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/26cbf89ccb7f</guid>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[flutter-ntp]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ntp]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 12:51:21 GMT</pubDate>
            <atom:updated>2025-06-24T07:17:19.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>🕰️ Flutter’s DateTime.now() vs NTP.now() – When Device Time Isn’t Good Enough</h3><p>In many Flutter apps, developers use DateTime.now() Assuming it always gives the correct time. But this trust can backfire when the device&#39;s clock is incorrect or manipulated.</p><p>That’s where NTP.now() comes in — it fetches accurate time from an NTP server, unaffected by the user’s system clock. But even NTP.now() isn’t foolproof unless used properly.</p><h3>📱 Why DateTime.now() isn’t Always Enough</h3><p>Here’s what can go wrong with DateTime.now():</p><ul><li>✅ <strong>User manually changes the system time</strong></li><li>✅ <strong>Device time drifts over days/weeks</strong></li><li>✅ <strong>Users travel across time zones</strong></li><li>✅ <strong>Clock gets auto-corrected mid-session</strong></li><li>✅ <strong>Malicious users spoof time for app behavior</strong></li></ul><p>For any app that depends on time-sensitive logic, this is a serious flaw.</p><h3>💡 Common Real-World Use Cases for Accurate Time</h3><h3>🛍️ 1. Flash Sales / Countdown Timers</h3><p>Apps like Amazon or Flipkart run lightning deals that end at specific times. Users could manipulate their phone clock to access an agreement after expiry.</p><h3>⏳ 2. Auctions or Bidding Systems</h3><p>Apps like eBay or in-house bidding platforms require precise bid timestamps. Using system time could allow “sniping” beyond the official deadline.</p><h3>🗓️ 3. Task Deadlines &amp; Attendance</h3><p>School, productivity, or work-tracking apps that log attendance or assignment submission must be immune to clock tampering.</p><h3>📩 4. Messaging / Chat Systems</h3><p>To order messages correctly across users in different time zones or with bad clocks, server-accurate time is essential.</p><h3>🛡️ 5. Security / Authentication Systems</h3><p>Time-based access (like OTP expiry, 2FA windows) must be trustworthy. If a user can rewind their device clock, it could bypass expiration logic.</p><h3>🌐 Meet NTP.now()</h3><p>The <a href="https://pub.dev/packages/ntp">ntp package</a> fetches time from trusted internet time servers.</p><pre>import &#39;package:ntp/ntp.dart&#39;;<br><br>DateTime now = await NTP.now();</pre><p>But simply calling NTP.now() Once isn&#39;t enough if the <strong>device clock changes later</strong>.</p><h3>🧨 The Hidden Problem: Device Time Can Change After You Sync</h3><p>Here’s a common mistake:</p><pre>final ntpTime = await NTP.now();<br>final localTimeAtSync = DateTime.now();<br><br>final elapsed = DateTime.now().difference(localTimeAtSync);<br>final currentAccurateTime = ntpTime.add(elapsed);</pre><p>If the device time is changed manually or auto-updated (e.g., time zone or NITZ adjustment), this method gets corrupted, because It DateTime.now() is no longer stable.</p><h3>✅ The Correct Way: Use Stopwatch (Monotonic Clock)</h3><p>Instead of relying on DateTime.now()</p><p>To track time passed, use Stopwatch, which gives <strong>monotonic, system-independent time</strong>.</p><h3>✅ Stable NTP Time with Stopwatch</h3><pre>import &#39;package:ntp/ntp.dart&#39;;<br><br>class TimeSyncService {<br>  static DateTime? _ntpTime;<br>  static final Stopwatch _elapsed = Stopwatch();<br>  /// Call once at app launch<br>  static Future&lt;void&gt; syncTime() async {<br>    try {<br>      _ntpTime = await NTP.now();<br>      _elapsed<br>        ..reset()<br>        ..start();<br>    } catch (e) {<br>      print(&quot;NTP sync failed: $e&quot;);<br>      _ntpTime = DateTime.now(); // fallback<br>      _elapsed<br>        ..reset()<br>        ..start();<br>    }<br>  }<br>  /// Use this to get stable time<br>  static DateTime now() {<br>    if (_ntpTime == null) return DateTime.now(); // fallback<br>    return _ntpTime!.add(_elapsed.elapsed);<br>  }<br>}</pre><h3>🔧 Usage in main.dart</h3><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await TimeSyncService.syncTime();<br>  runApp(MyApp());<br>}</pre><p>Anywhere in your app:</p><pre>final accurateNow = TimeSyncService.now();</pre><h3>🔁 Optional: Periodic Resync</h3><p>If your app stays open long or relies on high precision (e.g., over hours), you can resync time every few hours:</p><pre>Timer.periodic(Duration(hours: 6), (_) =&gt; TimeSyncService.syncTime());</pre><h3>✅ Key Advantages</h3><pre>| Method                      | Vulnerable to System Time Changes | Recommended  |<br>| --------------------------- | --------------------------------- | ------------ |<br>| `DateTime.now()`            | ✅ Yes                             | ❌ No         |<br>| `await NTP.now()` each time | ❌ Accurate, but expensive         | ⚠️ Sometimes |<br>| `NTP.now()` + `Stopwatch`   | ❌ No                              | ✅ Yes        |</pre><h3>🧠 Final Thoughts</h3><p>If your app uses time for anything critical — authentication, billing, bidding, deadlines, or chat — relying on device time can backfire. Combine NTP.now() with Stopwatch to ensure:</p><ul><li>✅ Trustworthy timestamps</li><li>✅ Immunity to clock tampering</li><li>✅ Lightweight, high-performance logic</li></ul><p>⏱️ <strong>Remember:</strong> It’s not just about <em>what</em> time it is — it’s about <em>who</em> you trust to tell you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26cbf89ccb7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Flutter Layout Struggles: Sticky Header + Smart Footer (That Doesn’t Break!)]]></title>
            <link>https://ashutoshagarwal2014.medium.com/flutter-layout-struggles-sticky-header-smart-footer-that-doesnt-break-140541cbec8e?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/140541cbec8e</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-sdk]]></category>
            <category><![CDATA[flutter-layout]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Sat, 31 May 2025 21:18:59 GMT</pubDate>
            <atom:updated>2025-05-31T21:18:59.898Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever tried to build a layout in Flutter where:</p><ul><li>You have a <strong>header</strong> that stays at the top,</li><li>A <strong>list of items</strong> or some content in the middle,</li><li>And a <strong>footer</strong> that <em>sticks to the bottom</em> if there’s space, but scrolls <em>after</em> the content if the page gets too long?</li></ul><p>Yeah, I did too. And it took way longer than it should’ve.</p><p>So let me save you the headache.</p><h3>🤔 The Problem</h3><p>At first, it sounds simple: header → content → footer. Just stack them in a Column, right?</p><p>But then you try to scroll. Or you use Expanded. Or maybe IntrinsicHeight. And boom — you get a lovely red error:</p><blockquote><em>“Vertical viewport was given unbounded height.”</em></blockquote><p>Or worse: your footer floats halfway up the screen when there’s not enough content to push it down. Not a great look.</p><h3>✅ What We’re Building</h3><p>Here’s what we want:</p><ul><li>A <strong>sticky header</strong> (like a page title or app bar),</li><li>Some <strong>scrollable content</strong> in the middle (like a list or form),</li><li>A <strong>footer</strong> that: Sits <strong>at the bottom of the screen</strong> if the page is short, scrolls <strong>after all content</strong> if the page is long.</li></ul><p>In short: footer sticks if there’s room, scrolls if not.</p><h3>🔨 The Working Solution</h3><p>Here’s the layout that finally worked for me — clean, no errors, behaves exactly as you’d expect:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class StickyHeaderWithFooter extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: LayoutBuilder(<br>        builder: (context, constraints) {<br>          return Column(<br>            children: [<br>              // Sticky Header<br>              Container(<br>                height: 100,<br>                color: Colors.blue,<br>                alignment: Alignment.center,<br>                child: Text(<br>                  &quot;Sticky Header&quot;,<br>                  style: TextStyle(color: Colors.white, fontSize: 20),<br>                ),<br>              ),<br><br>              // Scrollable content + footer<br>              Expanded(<br>                child: SingleChildScrollView(<br>                  child: ConstrainedBox(<br>                    constraints: BoxConstraints(<br>                      // Make sure the scroll view fills the screen if content is short<br>                      minHeight: constraints.maxHeight - 100, // header height<br>                    ),<br>                    child: Column(<br>                      mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>                      children: [<br>                        // Your content here<br>                        Column(<br>                          children: [<br>                            Container(height: 100, color: Colors.amber, child: Text(&quot;Item 1&quot;)),<br>                            Container(height: 100, color: Colors.green, child: Text(&quot;Item 2&quot;)),<br>                            // Add more items to test scroll behavior<br>                          ],<br>                        ),<br><br>                        // Footer<br>                        Container(<br>                          height: 60,<br>                          color: Colors.black,<br>                          alignment: Alignment.center,<br>                          child: Text(<br>                            &quot;Footer&quot;,<br>                            style: TextStyle(color: Colors.white),<br>                          ),<br>                        ),<br>                      ],<br>                    ),<br>                  ),<br>                ),<br>              ),<br>            ],<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>🧠 How This Works</h3><p>Let’s break it down:</p><ul><li>We wrap everything in a Column.</li><li>The <strong>header</strong> sits at the top, outside the scroll view, so it’s always visible.</li><li>The <strong>scrollable area</strong> contains both the main content and the footer.</li><li>The ConstrainedBox ensures that if the content is <em>short</em>, it stretches to fill the screen.</li><li>The mainAxisAlignment: spaceBetween inside the inner Column pushes the footer to the bottom when there’s extra space.</li></ul><p>This way, your footer will:</p><ul><li>Sit flush at the bottom of the screen if there’s not much content,</li><li>Or scroll naturally to the bottom when content is long.</li></ul><p>No hacks. No layout-breaking errors.</p><h3>💡 Bonus Tips</h3><ul><li>Want a real sticky AppBar? Use a SliverAppBar with CustomScrollView.</li><li>If your content is dynamic or in a list, replace the body Column with a ListView.builder, and be mindful of heights.</li><li>Test both short and long content scenarios — you’ll see the footer adapts beautifully.</li></ul><h3>🏁 Final Thoughts</h3><p>This kind of layout feels like it <em>should</em> be easy, but Flutter’s layout system requires a bit of careful setup. Now that you’ve got this pattern down, you can use it for:</p><ul><li>Onboarding screens</li><li>Settings pages</li><li>Forms with a submit button at the bottom</li><li>Anything where content length is unpredictable</li></ul><p>Let me know if you hit any edge cases — or if you’d like the code wrapped into a reusable widget!</p><p>Happy Fluttering! 🐦💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=140541cbec8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Import Assets from a Package in Flutter]]></title>
            <link>https://ashutoshagarwal2014.medium.com/how-to-import-assets-from-a-package-in-flutter-02adf82d4e59?source=rss-d6af75554eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/02adf82d4e59</guid>
            <category><![CDATA[flutter-sdk]]></category>
            <category><![CDATA[assets]]></category>
            <category><![CDATA[flutter-package]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app]]></category>
            <dc:creator><![CDATA[Ashutosh Agarwal]]></dc:creator>
            <pubDate>Wed, 14 May 2025 08:38:21 GMT</pubDate>
            <atom:updated>2025-05-14T08:38:21.931Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter makes it easy to include and manage assets like images, fonts, and JSON files within your app. But what if you want to use assets that come <strong>from a package</strong>?</p><p>In this article, we’ll explore how to <strong>import and use assets from a third-party Flutter package</strong> (or your own), and what to watch out for when doing so.</p><h3>💡 Why Use Package Assets?</h3><p>Many Flutter packages ship with their own assets — icons, animations, fonts, images, etc. Rather than copying these assets into your app, it’s cleaner and more maintainable to use them directly from the package.</p><p>For example, packages like rive, flutter_svg, or UI kits often include assets you’ll want to render directly in your app.</p><h3>📁 Step 1: Check if the Package Exposes Assets</h3><p>Before you try to use an asset from a package, make sure the package <strong>actually declares the asset</strong> in its pubspec.yaml.</p><p>A typical declaration looks like this:</p><pre>flutter:<br>  assets:<br>    - assets/images/logo.png</pre><p>If you’re unsure, check the pubspec.yaml in the package’s GitHub repo or in your .pub-cache directory.</p><h3>🔗 Step 2: Import the Asset Using packages/ Prefix</h3><p>To reference an asset from a package, use the following format:</p><pre>Image.asset(&#39;packages/&lt;package_name&gt;/&lt;asset_path&gt;&#39;);</pre><h3>✅ Example:</h3><p>Let’s say you’re using a package called awesome_ui and it includes an image at:</p><pre>assets/images/button_background.png</pre><p>You can render it like this:</p><pre>Image.asset(&#39;packages/awesome_ui/assets/images/button_background.png&#39;);</pre><p>This works because:</p><ul><li>The asset is declared in awesome_ui’s pubspec.yaml</li><li>You’re using the correct prefixed path</li></ul><h3>🎨 Fonts in Packages</h3><p>If you’re using <strong>custom fonts from a package</strong>, the process is a bit different.</p><p>The package should declare fonts like so:</p><pre>flutter:<br>  fonts:<br>    - family: FancyFont<br>      fonts:<br>        - asset: assets/fonts/FancyFont.ttf</pre><p>In your app, you can just use:</p><pre>Text(<br>  &#39;Hello!&#39;,<br>  style: TextStyle(fontFamily: &#39;FancyFont&#39;),<br>)</pre><p>You don’t need the packages/ prefix for fonts. Flutter handles it behind the scenes.</p><h3>🧑‍💻 What If You’re Building the Package?</h3><p>If you’re creating a package and want consumers to use your assets, <strong>you must list them explicitly</strong> in your own pubspec.yaml:</p><pre>flutter:<br>  assets:<br>    - assets/icons/<br>    - assets/images/</pre><p>Then, consumers can load them using the packages/ prefix as described earlier.</p><h3>❗ Common Pitfalls</h3><p>Here are a few things that can trip you up:</p><ul><li>❌ <strong>Wrong path:</strong> Double-check the asset path. It’s relative to the root of the package.</li><li>❌ <strong>Asset not declared:</strong> If the asset isn’t listed in pubspec.yaml, Flutter won&#39;t bundle it.</li><li>❌ <strong>Missing package name:</strong> You <em>must</em> include packages/your_package/ when loading assets from dependencies.</li></ul><h3>📦 Quick Recap</h3><p>Use Case Asset Path Format Your own asset &#39;assets/images/foo.png&#39; From a package &#39;packages/package_name/assets/images/foo.png&#39; Font from package &#39;FancyFont&#39; (use in TextStyle, no prefix needed)</p><h3>🏁 Final Thoughts</h3><p>Using assets from packages is a great way to modularize your Flutter app and reduce duplication. Just remember:</p><ul><li>Packages must declare their assets</li><li>Use the packages/package_name/ prefix</li><li>Fonts work slightly differently (and more seamlessly)</li></ul><p>If you’re publishing a package, <strong>exposing your assets properly</strong> makes your package more useful to the community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02adf82d4e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>