<?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 Shrihriday Bhagwat on Medium]]></title>
        <description><![CDATA[Stories by Shrihriday Bhagwat on Medium]]></description>
        <link>https://medium.com/@shreebhagwat94?source=rss-ae2241179909------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RmiWVHg17-QSWs9zu2nKPw.png</url>
            <title>Stories by Shrihriday Bhagwat on Medium</title>
            <link>https://medium.com/@shreebhagwat94?source=rss-ae2241179909------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:59:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shreebhagwat94/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[How to Make Your Flutter App Ready for iPhone Duo]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@shreebhagwat94/how-to-make-your-flutter-app-ready-for-iphone-duo-493dfe6fd465?source=rss-ae2241179909------2"><img src="https://cdn-images-1.medium.com/max/1600/1*kwDzJDzRW4s7Bqg1nFEKPw.png" width="1600"></a></p><p class="medium-feed-snippet">The iPhone Duo went on sale on October 23, 2026, and most Flutter apps are not ready for it.</p><p class="medium-feed-link"><a href="https://medium.com/@shreebhagwat94/how-to-make-your-flutter-app-ready-for-iphone-duo-493dfe6fd465?source=rss-ae2241179909------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@shreebhagwat94/how-to-make-your-flutter-app-ready-for-iphone-duo-493dfe6fd465?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/493dfe6fd465</guid>
            <category><![CDATA[iphone-duo]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 06:59:29 GMT</pubDate>
            <atom:updated>2026-10-24T06:59:29.455Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How would I learn Flutter in 2026 — The Future of App development.]]></title>
            <link>https://medium.com/@shreebhagwat94/how-would-i-learn-flutter-in-2026-the-future-of-app-development-f7a362f5acb9?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a362f5acb9</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 18:57:24 GMT</pubDate>
            <atom:updated>2025-12-30T18:57:24.669Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Flutter in 2026: Building High-Fidelity Apps in an AI-Augmented World</strong></h3><p>How would I learn Flutter in 2026 — The Future of App development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GueK3fjwIq-NepUoszzmg.png" /></figure><p>Mobile app development in 2026 looks nothing like it did even three years ago. The question is no longer <em>“Which framework should I learn?”</em> but rather <em>“How do I build high-quality apps in an AI-assisted world without losing engineering depth?”</em> Flutter still sits right in the middle of that conversation — misunderstood by beginners, underestimated by purists, and deeply relied upon by teams shipping serious products.</p><p>This blog is written for developers who are starting <strong>Flutter app development in 2026 from scratch</strong>, but who don’t want shallow tutorials, outdated advice, or blind optimism. It is written from the perspective of someone who has built native iOS apps, shipped large Flutter apps in production, and now actively works in an ecosystem dominated by <strong>Cursor, Copilot, Claude, Gemini, and ChatGPT-style agents</strong>.</p><h4>What Flutter Really Is in 2026 (Beyond the Elevator Pitch)</h4><p>Flutter is no longer “Google’s cross-platform UI toolkit” — that description stopped being useful years ago. In 2026, Flutter is best understood as a <strong>rendering-driven application framework</strong> that owns its UI pipeline end-to-end. This single design decision still defines everything Flutter does well — and everything it struggles with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8yxbV5tZLTzeQkniFq9ug.png" /></figure><p>Unlike React Native, Kotlin Multiplatform, or hybrid web wrappers, Flutter does not ask the operating system to draw buttons, lists, or layouts. Instead, it renders pixels directly using Skia (and increasingly Impeller), creating a deterministic UI layer that behaves identically across platforms. This is why Flutter apps feel consistent across Android, iOS, web, desktop, and embedded devices — and also why Flutter sometimes feels “alien” to native developers.</p><p>By 2026, Flutter is no longer experimental on desktop or web. Desktop Flutter apps are common in internal tools, admin panels, POS systems, and AI-powered dashboards. Flutter Web has matured enough for controlled environments and PWA-style use cases, though it still isn’t a full replacement for traditional web stacks.</p><p>The most important shift, however, is that Flutter has moved <strong>from being a UI framework to being an application platform</strong>. With strong ecosystem support around state management, offline-first sync, background execution, and AI integrations, Flutter apps today are far closer to native apps than most people still assume.</p><h4>The Reality of App Development in an AI-First World</h4><p>In 2026, <strong>nobody writes apps alone anymore</strong>. Cursor, GitHub Copilot, Claude, Gemini, and specialized AI agents are no longer “helpers” — they are collaborators. You can scaffold a full Flutter app in minutes, generate Riverpod providers instantly, refactor architecture automatically, and even generate UI animations from natural language prompts.</p><p>But here is the uncomfortable truth: <strong>AI has not replaced engineering skill — it has exposed the lack of it</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URiGhHZAm6Ue884MRpb0vg.png" /></figure><p>AI tools are extremely good at generating <em>syntactically correct Flutter code</em>. They are terrible at understanding <em>why</em> a widget tree is structured a certain way, <em>how</em> rebuilds affect performance, or <em>when</em> state should be hoisted versus localized. Developers who start Flutter in 2026 without understanding Flutter’s rendering model, widget lifecycle, and state propagation will ship apps that work — and then collapse under scale.</p><p>Flutter in the AI era rewards developers who understand fundamentals more than ever. Cursor can write a ConsumerWidget, but it cannot decide if your domain logic belongs in a use case, a provider, or a background isolate. AI can generate animations, but it won’t warn you when your implicit animations cause unnecessary rebuilds at 60fps.</p><p>If you are learning Flutter in 2026, <strong>AI is not optional — but blind trust in AI is dangerous</strong>.</p><h4>The Current State of Mobile Application Development</h4><p>Mobile app development itself has changed in shape, not relevance. Contrary to popular belief, mobile apps are not dying — they are becoming more specialized, more integrated, and more experience-driven.</p><p>Users expect apps to be fast, offline-capable, privacy-respecting, and visually polished. The “good enough” UI era is over. Apple, Google, and Microsoft now enforce stricter UX, security, and performance expectations. In this environment, frameworks are judged less by how fast you can build a demo and more by how reliably you can maintain a production app for five years.</p><p>Flutter survives here because it optimizes for <strong>long-term maintainability across platforms</strong>. Teams choose Flutter not because it is trendy, but because rewriting the same app three times (iOS, Android, Web) is economically unsustainable. Flutter trades some platform purity for engineering efficiency — and in 2026, that trade-off makes sense for a large class of products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zr4spCpbHlivoJ-X6FLH1w.png" /></figure><h4>Flutter vs React Native vs Kotlin Multiplatform</h4><p>The comparison landscape has evolved.</p><p>React Native in 2026 is still strong in teams deeply invested in the React ecosystem. However, it remains constrained by the JavaScript bridge, runtime unpredictability, and dependency fragility. With AI-generated code, React Native apps often become harder to debug because logic is split across JS, native modules, and build tooling.</p><p>Kotlin Multiplatform (KMP) has grown significantly and deserves respect. It shines when teams want to share business logic across Android, iOS, and backend services while keeping UI fully native. But KMP is <strong>not a UI solution</strong> — it is a shared logic solution. You still need deep expertise in SwiftUI and Compose, which doubles the UI effort.</p><p>Flutter sits in between. It does not give you native UI, but it gives you <strong>one UI with near-native control</strong>. For teams with limited resources, startups, and product-focused companies, this matters more than ideological purity.</p><p>In 2026, Flutter is not competing with KMP directly — it is solving a different problem.</p><h4>Flutter vs Native (Swift, Kotlin)</h4><p>Native development still wins when <strong>platform fidelity is non-negotiable</strong>. Apple’s newest APIs, visionOS features, deeply integrated system UI patterns, and experimental hardware capabilities will always arrive in Swift first. Kotlin remains unmatched for low-level Android system integration.</p><p>Flutter lags here — and always will.</p><p>But Flutter excels where <strong>product consistency, development speed, and cross-platform coherence</strong> matter. Flutter’s animation system, layout engine, and declarative UI model allow teams to build complex, expressive interfaces faster than native teams in many cases — especially when AI assists with boilerplate.</p><p>A key truth many miss: Flutter does not try to replace native development. It tries to <strong>reduce the cost of product iteration</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*re07NwXfc-nYR1MIirOOfQ.png" /></figure><h4>Where Flutter Lags — Honestly</h4><p>Flutter still struggles with platform-specific nuances. iOS apps built in Flutter can feel “almost native” — but not always <em>emotionally native</em>. Scroll physics, navigation transitions, text rendering subtleties, and accessibility behavior sometimes need manual tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7FXLCfWxaiE88ukO5V_qw.png" /></figure><p>Heavy background processing, advanced audio/video pipelines, and system-level integrations still require platform channels or native plugins. Flutter Web, while improved, cannot match modern web frameworks for SEO-heavy or content-driven applications.</p><p>Flutter also demands architectural discipline. Without clear boundaries, Flutter apps become unmaintainable widget jungles — especially when AI generates code faster than developers can reason about it.</p><h3>Where Flutter Excels — Quietly and Powerfully</h3><p>Flutter’s greatest strengths are rarely the ones mentioned in marketing decks or beginner tutorials. Its true power reveals itself only when applications grow large, teams scale, features multiply, and requirements change faster than documentation can keep up. In 2026, Flutter excels not because it is flashy, but because it is <strong>predictable under pressure</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNYdzkWZ9HnebiFCzp8chg.png" /></figure><h4>Deterministic UI Rendering: The Most Underrated Advantage</h4><p>Flutter’s most misunderstood strength is its deterministic rendering model. Unlike native frameworks that rely on constraint solvers, platform UI abstractions, or indirect layout passes, Flutter owns its entire render pipeline. From widget to element to render object to pixels, every step is under Flutter’s control.</p><p>This matters deeply in real-world applications. When a layout breaks in Flutter, it breaks consistently. When an animation stutters, the cause can be traced using frame timelines. When text overflows, the rules are explicit. In large-scale apps, this predictability becomes a superpower. Teams stop fighting the platform and start reasoning about behavior.</p><p>In contrast, many native UI bugs are emergent — caused by OS updates, undocumented layout behavior, or edge-case system configurations. Flutter shields teams from much of that uncertainty by rendering everything itself.</p><h4>UI Consistency at Scale</h4><h4>As products grow, UI consistency becomes harder than feature development. Flutter excels here not by enforcing design systems, but by making inconsistency expensive. Because Flutter does not inherit platform widgets automatically, teams must consciously define typography, spacing, animation curves, and interaction behavior.</h4><p>This often feels like extra work at the beginning, but it pays off massively in mature products. Once a design language is encoded into Flutter widgets, it becomes impossible to accidentally violate it. Every screen inherits the same visual grammar. This is why Flutter apps often look more coherent than native apps built by multiple teams over time.</p><p>In 2026, where apps frequently ship AI-generated dynamic UIs, this consistency layer becomes even more important. Flutter acts as a stabilizing force around otherwise unpredictable UI generation.</p><h4>Animation as a First-Class Citizen.</h4><p>Flutter’s animation system is not an add-on — it is foundational. Animations in Flutter are not side effects; they are part of the widget tree. This allows complex transitions, gesture-driven animations, and physics-based motion to be expressed declaratively and controlled precisely.</p><p>What makes this powerful in 2026 is how well Flutter animations compose with AI-generated UI. Cursor or other agents can generate animation controllers, tweens, and transitions quickly, but Flutter’s architecture ensures that these animations remain performant and synchronized with the render pipeline.</p><p>Unlike web or hybrid frameworks where animations often fight layout or reflow, Flutter animations are predictable and frame-aligned. This is why Flutter continues to excel in apps where motion is not decorative but functional — dashboards, productivity tools, creative software, and AI-assisted interfaces.</p><h4>Offline-First and State-Heavy Applications</h4><p>Flutter shines quietly in applications that must handle <strong>complex state over unreliable networks</strong>. Combined with modern sync engines like PowerSync, Supabase, or custom CRDT-based solutions, Flutter becomes an ideal client for offline-first systems.</p><p>This is not accidental. Flutter’s reactive rebuild model naturally reflects state transitions, making it easier to reason about local vs remote data, optimistic updates, and eventual consistency. In 2026, when apps are expected to work seamlessly across devices, regions, and connectivity conditions, this becomes a decisive advantage.</p><p>Native frameworks can do this too — but Flutter’s unified codebase reduces the cognitive load dramatically.</p><h4>Long-Term Maintainability</h4><p>Perhaps Flutter’s greatest strength is not technical — it is economic. Flutter applications age well. Teams can onboard new developers faster. Refactors are safer because UI is declarative. Architecture patterns are transferable across platforms.</p><p>In a world where products are expected to live for 7–10 years, Flutter offers something rare: <strong>predictable maintenance cost</strong>.</p><h3>If You Want to Learn Flutter in 2026 — What Should You Actually Focus On?</h3><p>Learning Flutter in 2026 is not about copying widget trees from tutorials. That approach actively harms developers in an AI-driven ecosystem. The real challenge is learning <strong>how Flutter thinks</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*my4D82DLWM516_FXbBScYw.png" /></figure><h3>Understanding the Widget–Element–RenderObject Pipeline</h3><p>This is non-negotiable. Flutter developers who do not understand this pipeline will always feel lost when debugging rebuilds, performance issues, or layout bugs. Widgets are immutable configuration objects. Elements hold state. RenderObjects perform layout and painting.</p><p>Once this mental model clicks, Flutter stops feeling magical and starts feeling mechanical — in the best possible way. You understand why const matters. You understand why keys exist. You understand why some widgets rebuild and others don’t.</p><p>In 2026, AI will happily generate widget trees, but only developers who understand this pipeline can evaluate whether that generated code is efficient, correct, or dangerous.</p><h3>Rebuild Cost and Frame Budget Awareness</h3><p>Flutter runs at 60–120 frames per second. That gives you 8–16 milliseconds per frame. Every rebuild, layout pass, and paint operation eats into that budget.</p><p>Learning Flutter properly means learning how to <strong>budget time per frame</strong>. This includes knowing when to split widgets, when to memoize values, when to isolate state, and when to use repaint boundaries.</p><p>AI does not optimize for frame budgets — humans must.</p><h3>State Management as a Modeling Tool, Not a Library Choice</h3><p>By 2026, the debate between Bloc, Riverpod, and other state management solutions is largely settled: the tool matters less than the mental model. State management is about <strong>modeling change over time</strong>, not wiring streams.</p><p>You must learn how to identify:</p><ul><li>Ephemeral UI state</li><li>Persistent domain state</li><li>Remote-synced state</li><li>Derived state</li></ul><p>Flutter forces you to confront these distinctions early, and that is a gift. Developers who master state modeling in Flutter become better engineers in any framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXXACdGpIFDi6z_15--6XA.png" /></figure><h4>Architecture That Survives AI Code Generation</h4><p>AI accelerates code creation but amplifies architectural mistakes. If you do not define boundaries, AI will happily violate them.</p><p>Learning Flutter in 2026 means learning how to:</p><ul><li>Isolate domain logic from UI</li><li>Keep providers thin</li><li>Avoid widget-driven business logic</li><li>Design APIs that AI cannot easily misuse</li><li>Focus more on Native logs and issue native bugs.</li></ul><p>Clean Architecture is no longer academic — it is defensive programming against over-generation.</p><h4>Platform Literacy Still Matters</h4><p>Even if you never write Swift or Kotlin daily, you must understand platform behavior. Permissions, lifecycle, background execution, accessibility, and system UI constraints still matter.</p><p>Flutter does not replace platform knowledge — it abstracts it. Developers who ignore this end up blaming Flutter for platform mistakes.</p><h4>Flutter + AI: The Right Way Forward</h4><p>The biggest mistake developers make in 2026 is treating AI as a shortcut rather than a force multiplier. Flutter and AI together are powerful — but only when responsibilities are clearly divided.</p><h4>AI Writes Code, Humans Design Systems</h4><p>AI excels at producing code locally. It struggles with global reasoning. Flutter apps are systems — not scripts.</p><p>The correct workflow is:</p><ul><li>Humans define architecture, constraints, and invariants</li><li>AI generates implementations within those boundaries</li><li>Humans review, refactor, and enforce quality</li></ul><p>Flutter’s declarative nature makes this workflow especially effective. AI can generate widgets, providers, animations, and tests — but humans must ensure coherence.</p><h4>Prompting as an Engineering Skill</h4><p>In Flutter development, prompts become part of your toolchain. The quality of AI output is directly tied to how well you can describe intent, constraints, and context.</p><p>Developers who learn Flutter deeply can prompt AI precisely: specifying rebuild behavior, performance constraints, accessibility requirements, and platform nuances. This is a competitive advantage.</p><h4>Guardrails Over Autonomy</h4><p>Letting AI freely modify Flutter projects without guardrails is dangerous. Flutter apps grow fast, and mistakes compound.</p><p>The right approach is:</p><ul><li>Strict folder structures</li><li>Clear provider ownership</li><li>Explicit UI/domain boundaries</li><li>Tests that fail loudly</li></ul><p>Flutter’s strong typing and declarative UI make it easier to enforce these guardrails than many other frameworks.</p><h3>The Future: AI-Augmented Flutter Teams</h3><p>The future of Flutter development is not about replacing developers with AI. It is about redefining what a “team” even means. In 2026, a Flutter team is no longer a group of people writing code at different speeds. It is a <strong>human-led system design group augmented by AI agents that execute relentlessly and without fatigue</strong>.</p><p>This shift fundamentally changes how Flutter apps are conceived, built, reviewed, and maintained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfFXGCthaE-f8s5eVOoBHw.png" /></figure><h4>From Code Producers to System Designers</h4><p>Historically, Flutter developers were valued for how fast they could translate UI designs into widget trees, wire state management, and integrate APIs. In an AI-augmented environment, that skill becomes table stakes. Cursor, Copilot, Gemini, and Claude can already generate Flutter screens, providers, animations, and even tests faster than humans.</p><p>The new differentiator is <strong>system design literacy</strong>.</p><p>Senior Flutter engineers in 2026 are no longer measured by how many lines of Dart they write. They are measured by how well they:</p><ul><li>Define architectural boundaries that AI must not cross</li><li>Model state and domain logic clearly enough that AI can implement it safely</li><li>Recognize subtle performance, accessibility, and lifecycle issues in generated code</li></ul><p>Flutter becomes less about typing and more about <strong>curating behavior</strong>.</p><h4>The Shape of an AI-Augmented Flutter Team</h4><p>A modern Flutter team often consists of fewer humans but more responsibility per person. One senior Flutter engineer may work with multiple AI agents simultaneously — one generating UI variants, another refactoring providers, another writing integration tests.</p><p>This works because Flutter’s declarative model compresses complexity. A well-designed widget tree can express intent clearly, allowing AI to operate within guardrails. Poorly designed trees, however, collapse quickly under AI pressure.</p><p>The Flutter engineer becomes the <strong>conductor</strong>, not the orchestra.</p><h4>Architectural Discipline Becomes Non-Optional</h4><p>AI does not understand architecture. It understands patterns, repetition, and local correctness. This is why Flutter apps without strict architecture degrade faster when AI is involved.</p><p>In AI-augmented teams, Flutter architecture must be:</p><ul><li>Explicit</li><li>Enforced</li><li>Reviewable</li></ul><p>Clean Architecture, feature-first folder structures, and strict UI/domain separation stop being stylistic preferences. They become safety mechanisms.</p><p>When AI generates a provider, it must be obvious whether it belongs to the UI layer or domain layer. When AI modifies a widget, it must not accidentally introduce business logic. Flutter’s strong typing and widget immutability help here — but only if humans define the boundaries clearly.</p><h4>Flutter as an AI-Friendly Framework</h4><p>Flutter is unusually well-suited for AI collaboration, and this is not accidental. Declarative UI frameworks are easier for AI to reason about than imperative ones. Flutter widgets describe <em>what</em> the UI should be, not <em>how</em> to mutate it.</p><p>This aligns perfectly with large language models, which excel at declarative reasoning.</p><p>When an AI generates Flutter code, it can reason in terms of composition, hierarchy, and configuration. This is much harder in imperative UI systems where side effects dominate.</p><p>Flutter’s widget tree is, effectively, a <strong>prompt-friendly UI DSL</strong>.</p><h4>AI as a State Transformer</h4><p>One of the most powerful patterns is treating AI not as a UI feature, but as a <strong>state transformation engine</strong>. User input becomes raw state. AI processes it. Flutter rebuilds based on the transformed state.</p><p>For example, in task management, note-taking, or productivity apps, raw user input is passed through an AI layer that extracts intent, structure, and metadata. Flutter does not render “AI responses” — it renders <strong>updated state models</strong>.</p><p>This keeps AI deterministic from the UI’s perspective and avoids brittle conversational UIs.</p><h4>AI-Driven UI Generation with Guardrails</h4><p>In advanced Flutter apps, AI can dynamically generate UI layouts based on context, user behavior, or domain rules. Flutter’s widget composition model makes this safe — as long as generation is constrained.</p><p>The UI is generated from structured schemas, not raw text. AI outputs JSON or strongly typed models. Flutter converts those into widgets.</p><p>This pattern avoids the chaos of AI writing widgets directly at runtime, while still enabling adaptive interfaces.</p><h4>On-Device vs Cloud AI in Flutter</h4><p>Flutter teams in 2026 must decide where intelligence lives. On-device AI provides privacy and low latency but limited capability. Cloud AI provides power but introduces latency and trust concerns.</p><p>Flutter’s cross-platform nature makes hybrid approaches viable. Lightweight models can run on device for classification, routing, and filtering, while heavier reasoning happens in the cloud.</p><p>The Flutter app becomes the <strong>orchestrator</strong> of intelligence, not the intelligence itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AT05ktHpabhkZTws1MqUg.png" /></figure><h4>AI-Generated Code Requires Human-Grade Reviews</h4><p>One of the most dangerous myths is that AI-generated Flutter code needs less review. It needs <strong>more</strong>.</p><p>AI often generates code that works but violates subtle best practices:</p><ul><li>Over-rebuilding widgets</li><li>Misusing FutureBuilder or StreamBuilder</li><li>Leaking controllers</li><li>Ignoring accessibility semantics</li><li>Breaking platform conventions</li></ul><p>In AI-augmented teams, code reviews shift from syntax checking to <strong>intent verification</strong>. Reviewers ask: <em>Is this the right abstraction? Is this the right lifecycle? Is this future-proof?</em></p><p>Flutter’s explicit lifecycle makes these reviews possible — but only if engineers understand it deeply.</p><h4>Testing in an AI-Augmented Flutter World</h4><p>AI changes testing expectations. Unit and widget tests can be generated quickly, but test <strong>quality</strong> still depends on human intent.</p><p>Flutter teams must design test boundaries before AI writes tests. Otherwise, AI tests mirror AI mistakes.</p><p>Golden tests, integration tests, and performance benchmarks become more important, not less. Flutter’s tooling excels here, but only disciplined teams benefit from it.</p><h4>Productivity Gains Without Quality Loss</h4><p>The real promise of AI-augmented Flutter teams is not speed — it is <strong>sustained quality at scale</strong>.</p><p>Flutter already reduces platform duplication. AI reduces repetitive coding. Together, they allow teams to spend more time on product decisions, UX fidelity, and long-term maintainability.</p><p>This is not about doing more work. It is about doing <strong>better work</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FtQUk4XMdA1083xS__6hg.png" /></figure><h3>Closing Thoughts</h3><p>Flutter in 2026 is no longer a framework you choose because you want to move fast or avoid writing native code twice. It is a framework you choose when you care about <strong>control, consistency, and long-term product clarity</strong> in an increasingly automated world. As AI becomes capable of writing code at scale, the value of Flutter shifts away from productivity alone and toward <strong>engineering discipline</strong>.</p><p>The real advantage of Flutter today is not that it hides platforms, but that it forces you to think clearly about UI, state, and behavior. Its declarative model exposes intent. Its rendering pipeline rewards understanding. And its ecosystem, when used thoughtfully, enables teams to build complex, offline-first, AI-powered applications without drowning in fragmentation.</p><p>Learning Flutter in 2026 is therefore not about memorizing widgets or following tutorials. It is about developing the ability to <strong>reason about systems</strong> — how data flows, how UI reacts, how performance degrades, and how architecture survives change. AI will happily generate code, but only engineers who understand these fundamentals will be able to shape that code into something durable.</p><p>The future of Flutter belongs to teams who treat AI as a collaborator, not a crutch. Teams who design boundaries before writing code. Teams who value clarity over cleverness and craftsmanship over speed. Flutter does not compete with AI — it complements it. Together, they raise the bar for what well-built applications look like.</p><p>Flutter is not standing still. It is growing up. And for developers willing to grow with it, 2026 is not the end of Flutter’s story — it is the beginning of its most important chapter.</p><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Q6NW0VDfM1euwP7W16vK_A.gif" /></figure><figure><a href="https://buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/1*DUreAUtI7Mxkg9RjzUiyvQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a362f5acb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Dynamic AI-Driven Interfaces with Flutter GenUI]]></title>
            <link>https://medium.com/@shreebhagwat94/building-dynamic-ai-driven-interfaces-with-flutter-genui-6bb41f26e0d2?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bb41f26e0d2</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 04:51:25 GMT</pubDate>
            <atom:updated>2025-12-29T04:51:25.263Z</atom:updated>
            <content:encoded><![CDATA[<p>A Deep Technical Exploration Using a Travel Planner.</p><p><a href="https://blog.flutter.dev/rich-and-dynamic-user-interfaces-with-flutter-and-generative-ui-178405af2455">Here is a small introduction blog on Gen-UI written by the Flutter team</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVLJ013SMes_zeUPfnOtug.png" /></figure><h3>Part 1: The UI Problem We’ve Been Quietly Living With</h3><p>From the moment you write your first build() method, Flutter teaches you to think deterministically: every widget is explicit, every layout decision intentional, every state transition carefully orchestrated. This is one of Flutter’s greatest strengths. It gives developers confidence that what they describe is exactly what users will see.</p><p>But over the last few years, something subtle has changed — not in Flutter, but in <strong>user expectations</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgS_OqV682nlhrZdKuNewQ.png" /></figure><p>Modern users no longer think in terms of screens and flows. They think in terms of <em>intent</em>. They don’t wake up wanting to “navigate to tab three, open a filter sheet, select checkboxes, and confirm a form.” They wake up wanting outcomes. They want to say:</p><blockquote><em>“Plan a relaxed 4-day Singapore trip with my toddler, keep it under ₹1 lakh.”</em></blockquote><p>And they expect the app to <em>meet them there</em>.This is where traditional UI paradigms start to crack.</p><p>Because the moment you try to model intent-driven behavior using static UI, you end up with an explosion of permutations. Every possible combination of preferences, constraints, and edge cases needs to be anticipated upfront. The UI grows not linearly, but combinatorially.</p><p>As Flutter developers, we respond by adding:</p><ul><li>More conditional widgets</li><li>More state</li><li>More branching logic</li><li>More screens</li></ul><p>The app still works — but it becomes harder to reason about, harder to evolve, and increasingly disconnected from how users actually think.</p><p>This is not a Flutter problem.<br>This is a <strong>UI paradigm problem</strong>.</p><h4>Part 2: Why “Just Add a Chatbot” Is an Incomplete Solution</h4><p>When generative AI entered mainstream product development, the industry’s first instinct was obvious: add a chat interface. Chat is natural. Chat is flexible. Chat lets users express intent without friction. So teams embedded chatbots into apps and called it “AI-powered UX.” But very quickly, cracks appeared. Chat is excellent at <strong>language</strong>. It is terrible at <strong>interaction design</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgPVjcTtNxmQ0G2_JnSDcQ.png" /></figure><p>Let’s take the same travel example, but imagine it as a pure chat experience.</p><p>The user types:</p><blockquote>“Plan a 4-day Singapore trip with a toddler.”</blockquote><p>The AI responds with a long paragraph:</p><ul><li>Mentions dates</li><li>Mentions budget assumptions</li><li>Lists attractions</li><li>Suggests hotels</li><li>Adds disclaimers</li></ul><p>Now the user wants to change just one thing:</p><blockquote><em>“Make it more relaxed and reduce walking.”</em></blockquote><p>In a chat-only interface, this forces a full regeneration. Context is implicit. Changes are fragile. Important constraints get lost in scrollback. The UI offers no affordances to <em>manipulate</em> the plan — only to <em>talk about</em> it.</p><p>This creates a paradox:</p><ul><li>The AI understands intent</li><li>But the UI gives the user no structure to refine it.</li></ul><p>Humans are visual and tactile creatures. We don’t just want answers — we want <strong>controls</strong>. Sliders. Chips. Toggles. Cards. Timelines. Chat alone cannot provide that. But traditional UI alone cannot handle open-ended intent. Something needs to sit in between.</p><h3>Part 3: Generative UI — Not “UI from JSON”, but a New Contract</h3><p>This is where <strong>Generative UI (GenUI)</strong> enters — and it’s important to be very clear about what it <em>is</em> and what it <em>is not</em>.</p><p>GenUI is not:</p><ul><li>Server-driven UI from arbitrary JSON</li><li>AI hallucinating widget trees</li><li>A replacement for Flutter’s rendering system</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqCvAY1M-NBtZZAs23MQ9w.png" /></figure><p>GenUI is a <strong>contract</strong>.</p><p>A contract between:</p><ul><li>The developer</li><li>The AI model</li><li>The Flutter framework</li></ul><p>In this contract, the developer defines the <em>rules of the world</em>. The AI is allowed to operate only within those rules.</p><p>Instead of saying:</p><blockquote>“Here is the UI”</blockquote><p>The developer says:</p><blockquote>“Here are the UI building blocks you may use, here are the regions where they may appear, and here is how user interaction flows back to you.”</blockquote><p>Flutter GenUI operationalizes this idea through four core concepts: <strong>catalogs, surfaces, conversations, and events</strong>. Together, they create a closed, safe, and deterministic loop where UI can be generated dynamically without sacrificing control.</p><h4>The Mental Shift Flutter Developers Must Make</h4><p>In traditional Flutter development, the widget tree is the source of truth. Everything flows from it. In GenUI, the <strong>intent model</strong> becomes the source of truth, and the widget tree becomes a <em>projection</em> of that intent at a given moment in time. This is a profound shift. It means the UI is no longer something you fully specify upfront. Instead, you design a <strong>system that produces UI</strong>. Flutter GenUI doesn’t ask you to give up control — it asks you to move that control <em>up a level</em>.</p><blockquote>You stop designing screens.<br>You start designing <strong>capabilities</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wSZ_F9HsTZs5urrOqR1pA.png" /></figure><h3>Introducing MyTrip: A GenUI-First Travel Planner</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IUEP7QGo-NYpsCZb5e9zA.png" /></figure><p><strong>MyTrip</strong> is a reference application built to explore this exact space.</p><p>Instead of asking the user to fill forms, MyTrip starts with a single open-ended input. From there, the UI grows organically — not arbitrarily, but within carefully defined constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NS3z2N8tVSsX_eHpKQzyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfKu6LZlzS0gT472gDkrlQ.png" /></figure><p>As the user interacts:</p><ul><li>Chips toggle preferences</li><li>Itineraries reflow</li><li>Options adapt</li></ul><p>All without navigation resets, modal explosions, or screen rewrites.</p><p>Flutter remains firmly in control of rendering. The AI remains firmly constrained by the catalog. The user remains firmly in control of intent.</p><h3>Part 4: From Theory to Architecture — How a GenUI App Is Actually Shaped</h3><p>When engineers hear “AI-generated UI”, the first instinct is skepticism — and rightly so. Flutter engineers are trained to distrust anything that claims to generate widgets dynamically without explicit control. The genui_onboarding_clean repository is interesting precisely because it does <strong>not</strong> try to be clever. It treats GenUI as a subsystem, not a replacement for Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8734BKAx2ygMrdjDfE-7A.png" /></figure><p>At the entry point, the app still looks like a normal Flutter application.</p><pre>void main() {<br>  runApp(const PlanMyTripApp());<br>}</pre><p>There is no global AI singleton. No hidden runtime magic. The app shell is ordinary and predictable, which is essential because GenUI must <strong>live inside</strong> a stable application, not become the application.</p><pre>class PlanMyTripApp extends StatelessWidget {<br>  const PlanMyTripApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;MyTrip – GenUI Demo&#39;,<br>      theme: ThemeData(<br>        useMaterial3: true,<br>        colorSchemeSeed: Colors.indigo,<br>      ),<br>      home: const PlannerScreen(),<br>    );<br>  }<br>}</pre><p>This matters more than it appears. GenUI does not control navigation, theming, routing, lifecycle, or error boundaries. Flutter does. This separation is the first thing that makes the system production-safe.</p><h4>Initializing GenUI Explicitly (No Magic)</h4><p>GenUI is initialized deliberately and visibly. The repository does <strong>not</strong> hide this inside providers or service locators. Instead, it makes the dependency graph explicit.</p><pre>late final GenUiManager genUiManager;<br>late final GenUiConversation conversation;</pre><p>These are created once, owned by the screen, and disposed predictably.</p><pre>@override<br>void initState() {<br>  super.initState();<br><br>  final catalog = CoreCatalogItems.asCatalog();<br><br>  genUiManager = GenUiManager(catalog: catalog);<br><br>  final generator = GoogleGenerativeAiContentGenerator(<br>    catalog: catalog,<br>    modelName: &#39;models/gemini-2.5-flash&#39;,<br>    systemInstruction: travelSystemInstruction,<br>  );<br><br>  conversation = GenUiConversation(<br>    contentGenerator: generator,<br>    genUiManager: genUiManager,<br>  );<br>}</pre><p>There are several subtle but important decisions here:</p><p>First, <strong>the catalog is created before the model</strong>. This enforces a strict rule: the model never exists without constraints. The AI never gets a chance to “free-think” UI. It can only operate within the catalog.</p><p>Second, the systemInstruction is injected once, not rewritten dynamically. This keeps behavior stable and prevents prompt drift over time.</p><p>Third, GenUiConversation becomes the <strong>single stateful authority</strong> for UI evolution. Flutter rebuilds do not recreate it, which prevents accidental resets.</p><h4>Surfaces as Explicit UI Anchors</h4><p>Rendering the UI is intentionally boring — and this is one of the best design choices in the repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eI-bv3NXYkKnLB21DMEiw.png" /></figure><pre>final host = conversation.host;</pre><p>The host is passed directly to surfaces.</p><pre>ListView(<br>  padding: const EdgeInsets.all(16),<br>  children: const [<br>    _Surface(id: &#39;trip_overview&#39;),<br>    _Surface(id: &#39;trip_controls&#39;),<br>    _Surface(id: &#39;itinerary&#39;),<br>    _Surface(id: &#39;options&#39;),<br>  ],<br>);</pre><p>Each surface is a real Flutter widget:</p><pre>class _Surface extends StatelessWidget {<br>  final String id;<br><br>  const _Surface({required this.id});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Padding(<br>      padding: const EdgeInsets.only(bottom: 12),<br>      child: GenUiSurface(<br>        host: context.read&lt;GenUiConversation&gt;().host,<br>        surfaceId: id,<br>      ),<br>    );<br>  }<br>}</pre><p>This matters because:</p><ul><li>Flutter owns layout</li><li>Flutter owns scrolling</li><li>Flutter owns rebuilds</li></ul><p>GenUI only provides <strong>content</strong>.</p><p>This design choice avoids a whole class of problems seen in server-driven UI systems where layout, rendering, and interaction become entangled.</p><h3>Part 5: Conversation Lifecycle &amp; Intent Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUDwQRz99jeCR0woP2oxxg.png" /></figure><p>So far, everything we’ve discussed could still feel somewhat abstract. Catalogs, surfaces, conversations — these are architectural primitives. The real magic of GenUI emerges when the <strong>interaction loop</strong> starts running. This is where MyTrip stops being a demo and starts feeling like a product.</p><h4>Intent Without Structure</h4><p>The MyTrip experience begins with deliberate emptiness. There is no form. No onboarding wizard. No checklist of requirements. Just a single text input. The user types something like:</p><blockquote><em>“Plan a 4-day Singapore trip in February, budget ₹1L, traveling with a toddler.”</em></blockquote><p>At this moment, the app knows almost nothing in a structured sense. There are dates implied but not fixed. A budget range is suggested but not precise. Preferences are hinted at but not enumerated. And this is intentional. Instead of forcing the user to clarify everything upfront, MyTrip allows ambiguity to exist — because ambiguity is where GenUI shines.</p><h4>The MyTrip planner does not “chat”. It <strong>converses with intent</strong>.</h4><p>The only place where raw user language enters the system is this function:</p><pre>void submitUserIntent(String text) {<br>  conversation.sendRequest(<br>    UserMessage.text(text),<br>  );<br>}</pre><p>This function is intentionally dumb.</p><p>There is no parsing, no NLP preprocessing, no heuristics. That responsibility belongs entirely to the AI model — constrained by the catalog.</p><p>Why is this important?</p><p>Because every additional interpretation layer you add here:</p><ul><li>Reduces flexibility</li><li>Introduces bugs</li><li>Duplicates model reasoning</li></ul><p>GenUI is designed to let the model reason <em>within constraints</em>, not to fight it.</p><h4>Why Events Matter More Than Prompts.</h4><p><strong>GenUI widgets</strong>.</p><p>A budget slider, for example, does not stream values. It emits a semantic event:</p><pre>onChangedEnd: (value) {<br>  GenUiEvent.emit(<br>    name: &#39;budget_updated&#39;,<br>    payload: {<br>      &#39;budget&#39;: value,<br>    },<br>  );<br>}</pre><p>This event is injected into the same conversation context as the original prompt. The model now reasons with <strong>structured intent</strong>, not language.</p><p>This is the key reason GenUI scales better than chat-based UX:</p><ul><li>Language is ambiguous</li><li>Events are explicit</li><li>UI state remains synchronized.</li></ul><h3>Part 6: Custom Widgets — Teaching the Model How to Think in UI</h3><p>Up to this point, MyTrip has relied primarily on the <strong>CoreCatalogItems</strong> that ship with Flutter GenUI. This is intentional. The core catalog allows you to validate the interaction loop, understand surfaces, and observe how a model reasons about layout without introducing additional variables.</p><p>But no real product survives on generic widgets alone.At some point, your UI must express <strong>domain meaning</strong>.A budget slider in a travel app is not the same thing as a generic slider. An itinerary card is not just a list item.<br>A hotel option is not interchangeable with a random card component.This is where GenUI’s most powerful idea quietly emerges:</p><blockquote>You don’t prompt the model to “design UI.”<br>You <strong>teach it a vocabulary</strong> that reflects your product’s domain.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzXHbRLQeCGPVlH869XjYA.png" /></figure><h4>Why Custom Widgets Are Non-Negotiable</h4><p>Many developers assume that GenUI’s intelligence comes primarily from the model. In practice, most of the intelligence comes from the <strong>catalog design</strong>. If your catalog is vague, the UI will feel vague. If your catalog is expressive, the UI will feel intentional.</p><p>In MyTrip, travel planning revolves around a few core concepts:</p><ul><li>A trip has a destination, duration, and overall character</li><li>Preferences are adjustable and interdependent</li><li>Itineraries are temporal and hierarchical</li><li>Options involve tradeoffs, not absolutes</li></ul><p>Trying to represent all of this using only generic text blocks and lists leads to UI that technically works, but feels flat. The model understands the intent, but it has no way to express it <em>visually</em> in a way that aligns with the product. Custom widgets close that gap.</p><h4>Designing Widgets for AI Consumption (Not Just for Humans)</h4><p>When Flutter developers design widgets, we usually think about:</p><ul><li>Visual hierarchy</li><li>Layout constraints</li><li>Reusability</li><li>Performance</li></ul><p>With GenUI, there is an additional audience:</p><p><strong>The AI model itself.</strong></p><p>A GenUI widget is not just a visual component. It is:</p><ul><li>A schema</li><li>A semantic signal</li><li>A decision-making affordance</li></ul><p>When you design a widget for GenUI, you are implicitly answering this question for the model:</p><blockquote><em>“When should I use this instead of something else?”</em></blockquote><p>This is why small, narrowly scoped widgets outperform large, flexible</p><h4>A Concrete Example: TripSummaryCard</h4><p>In a traditional Flutter app, a trip summary might be composed inline using rows, text widgets, and icons. In GenUI, that composition should be elevated into a <strong>single semantic unit</strong>.</p><p>Conceptually, a TripSummaryCard says:</p><pre>final tripSummarySchema = JsonSchema.object(<br>  properties: {<br>    &#39;destination&#39;: JsonSchema.string(),<br>    &#39;days&#39;: JsonSchema.integer(minimum: 1),<br>    &#39;budget&#39;: JsonSchema.integer(),<br>    &#39;travelStyle&#39;: JsonSchema.string(),<br>  },<br>  required: [&#39;destination&#39;, &#39;days&#39;],<br>);</pre><blockquote><em>“This represents the current understanding of the trip at a glance.”</em></blockquote><p>It might contain:</p><ul><li>Destination</li><li>Duration</li><li>Budget range</li><li>Travel style (family, solo, relaxed, fast-paced)</li></ul><p>From the model’s perspective, this is powerful. It no longer has to decide how to assemble these pieces. It only has to decide <em>whether</em> this summary should be shown, and <em>with what data</em>.</p><p>The widget schema enforces clarity.</p><h4>Creating the Catalog Item</h4><pre>final tripSummaryItem = CatalogItem(<br>  name: &#39;trip_summary_card&#39;,<br>  description: &#39;Displays a concise summary of the current trip&#39;,<br>  schema: tripSummarySchema,<br>  builder: (context, data) {<br>    return Card(<br>      child: ListTile(<br>        title: Text(data[&#39;destination&#39;]),<br>        subtitle: Text(<br>          &#39;${data[&#39;days&#39;]} days • ₹${data[&#39;budget&#39;]} • ${data[&#39;travelStyle&#39;]}&#39;,<br>        ),<br>      ),<br>    );<br>  },<br>);</pre><p>Once this is added to the catalog, the model can <em>choose</em> to use it — but cannot misuse it.</p><p>This is not “AI designing UI”.<br>This is <strong>AI assembling components you designed</strong>.</p><h3>Schemas as Guardrails, Not Bureaucracy</h3><p>A common fear when developers see schema definitions is that they feel verbose or restrictive. In GenUI, schemas are not bureaucracy — they are <strong>guardrails</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_s_61oMuknNSmLxj7YofA.png" /></figure><p>They ensure:</p><ul><li>The model cannot invent fields</li><li>The UI always receives valid data</li><li>Regeneration does not drift over time</li></ul><p>For example, defining a schema for a DayItineraryCard forces the model to think in terms of:</p><ul><li>A day index</li><li>A list of activities</li><li>Optional pacing metadata</li></ul><p>Instead of describing a day in prose, the model must <em>structure</em> it.</p><p>This is the difference between:</p><ul><li>“AI describing a plan”</li><li>“AI assembling a plan”</li></ul><h4>Why Smaller Widgets Scale Better Than Flexible Ones ?</h4><p>One tempting approach is to create a single “万能” widget that can display anything. This is almost always a mistake.</p><p>Flexible widgets push decision-making back onto prompts. Narrow widgets push decision-making into code.</p><p>GenUI works best when:</p><ul><li>Widgets are opinionated</li><li>Schemas are strict</li><li>Responsibilities are narrow</li></ul><p>This leads to:</p><ul><li>More predictable output</li><li>Easier debugging</li><li>Better UX consistency</li></ul><p>In MyTrip, it is far better to have:</p><ul><li>BudgetControl</li><li>PaceToggle</li><li>PreferenceChips</li><li>ItineraryDayCard</li></ul><p>…than one generic “TravelControlWidget” with dozens of optional fields. The AI doesn’t need flexibility. It needs <strong>clarity</strong>.</p><h4>Why This Is Safer Than Server-Driven UI</h4><p>In server-driven UI:</p><ul><li>JSON defines layout</li><li>Backend controls structure</li><li>Frontend becomes a renderer</li></ul><p>In GenUI:</p><ul><li>Frontend defines structure</li><li>AI chooses composition</li><li>Flutter remains authoritative</li></ul><p>That inversion is subtle — and powerful.</p><h3>Part 7: Controlling Regeneration — Making GenUI Feel Deterministic</h3><p>One of the biggest fears developers have when introducing AI into UI is unpredictability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DYJK8LFLiBjJwFHuXOSpA.png" /></figure><p><strong>The What if …</strong></p><p>What if the UI changes too much?<br>What if components jump around?<br>What if the model “forgets” decisions?</p><p>These fears are valid — and they are precisely why GenUI introduces <strong>structural constraints</strong>. When GenUI feels chaotic, it is almost always because the system lacks <strong>stability anchors</strong>.</p><h4>Stability Is Not an Accident</h4><p>In MyTrip, stability comes from three places:</p><ol><li>Stable surface IDs</li><li>Narrow widget responsibilities</li><li>Event-driven updates instead of full regeneration</li></ol><p>Let’s unpack why each matters.</p><h4>Stable Surfaces as Psychological Anchors</h4><p>Users form mental models quickly.</p><p>If “Trip Overview” always appears at the top, users trust it.<br>If “Controls” always live below it, users explore confidently.<br>If the itinerary stays in one region, users scan instead of searching.</p><p>Even if the content inside those surfaces changes, the <em>structure</em> remains familiar.</p><p>This is why surfaces should almost never be created or destroyed dynamically after the first render. Their contents may evolve, but their existence should be stable. From an implementation perspective, this is trivial. From a UX perspective, it is transformative.</p><h4>The Conversation Is the Single Source of Truth</h4><p>At runtime, exactly one object owns the evolving intent state:</p><pre>final GenUiConversation conversation;</pre><p>Every interaction flows through this object.</p><ul><li>User input → conversation.sendRequest</li><li>Widget interaction → GenUiEvent</li><li>AI response → surface update</li></ul><p>There is no parallel state graph. No duplicated “AI state” and “UI state”. Everything funnels through the conversation. This is why GenUI does not feel chaotic.</p><p>When a GenUI widget emits an event, it does <strong>not</strong> call your Flutter callbacks directly. Instead, it sends a structured signal into the conversation.</p><p>Conceptually, this is what happens:</p><pre>GenUiEvent.emit(<br>  name: &#39;pace_changed&#39;,<br>  payload: {<br>    &#39;pace&#39;: &#39;relaxed&#39;,<br>  },<br>);</pre><p>That event is appended to the conversation context and sent back to the model <em>together with</em> prior intent and constraints.</p><p>The key insight here is that <strong>events are additive</strong>, not destructive. They do not replace prior intent — they refine it. This mirrors how humans refine plans in real life.</p><h4>Why You Should Never Send Raw Widget State</h4><p>A common beginner mistake is to send raw UI state back to the model:</p><pre>// ❌ Bad<br>onChanged: (value) {<br>  conversation.sendRequest(<br>    UserMessage.text(&#39;Slider changed to $value&#39;),<br>  );<br>}</pre><p>This is dangerous because:</p><ul><li>It bloats tokens</li><li>It introduces ambiguity</li><li>It mixes UI noise with intent</li></ul><p>Instead, GenUI widgets should emit <strong>semantic events</strong>:</p><pre>// ✅ Good<br>onChangedEnd: (value) {<br>  GenUiEvent.emit(<br>    name: &#39;budget_updated&#39;,<br>    payload: {&#39;budget&#39;: value},<br>  );<br>}</pre><h4>Stability Through Surface-Scoped Regeneration.</h4><p>Another critical design decision in MyTrip is <strong>surface-scoped regeneration</strong>. When an event is emitted, the model does <em>not</em> regenerate the entire UI. It regenerates only the surfaces that need to change. This is why surfaces are defined up front and never dynamically created:</p><pre>const travelSurfaces = [<br>  &#39;trip_overview&#39;,<br>  &#39;trip_controls&#39;,<br>  &#39;itinerary&#39;,<br>  &#39;options&#39;,<br>];</pre><pre>for (final surface in travelSurfaces)<br>  GenUiSurface(<br>    host: conversation.host,<br>    surfaceId: surface,<br>  );</pre><p>This ensures that:</p><ul><li>Layout remains stable</li><li>Scrolling position is preserved</li><li>Cognitive load is minimized</li></ul><h4>Event-Driven Updates vs Prompt Rewrites</h4><p>A subtle but critical design choice in MyTrip is how user interactions are fed back into the model.</p><p>Instead of rephrasing everything as text —</p><blockquote><em>“User changed the budget to 90k and wants fewer walking activities”</em></blockquote><p>— GenUI emits <strong>structured events</strong>.</p><p>These events are:</p><ul><li>Typed</li><li>Contextual</li><li>Precise</li></ul><p>This precision dramatically reduces hallucination and drift. The model is no longer guessing what changed. It knows exactly what changed. This is why sliders and toggles matter so much in GenUI apps. They are not just UI controls — they are <strong>intent stabilizers</strong>.</p><h4>Preventing UI Thrashing</h4><p>UI thrashing happens when small changes cause large regenerations.</p><p>Common causes include:</p><ul><li>Overly broad prompts</li><li>Flexible schemas</li><li>Too few surfaces</li><li>Stateless conversations</li></ul><p>MyTrip avoids this by:</p><ul><li>Localizing changes to relevant surfaces</li><li>Avoiding global reflows</li><li>Maintaining conversation state explicitly</li></ul><p>The result is a UI that evolves smoothly instead of jumping unpredictably.</p><h4>Why Determinism Matters More Than Creativity.</h4><p>A mistake many teams make early is optimizing for “creative” AI output. This is appropriate for writing tools and ideation apps.</p><p>It is not appropriate for <strong>interfaces</strong>.</p><p>In UI, users value:</p><ul><li>Predictability</li><li>Learnability</li><li>Trust</li></ul><p>GenUI should feel adaptive, not surprising.</p><p>This is why the system instruction in MyTrip emphasizes:</p><ul><li>Structured UI over prose</li><li>Incremental refinement over wholesale regeneration</li><li>Conservatism in layout choices</li></ul><p>Creativity belongs in <em>content</em>. UI belongs in <em>systems</em>.</p><h4>The Hidden Win: Debuggability</h4><p>One of the least discussed advantages of GenUI done correctly is how <strong>debuggable</strong> it becomes.</p><p>Because:</p><ul><li>Widgets are typed</li><li>Events are structured</li><li>Surfaces are isolated</li></ul><p>You can:</p><ul><li>Log inputs and outputs</li><li>Reproduce issues</li><li>Compare regenerations</li><li>Write tests around catalog behavior</li></ul><p>This is impossible in chat-only systems. GenUI, when architected well, is actually <em>more testable</em> than traditional UI flows — not less.</p><p><strong>At this point, MyTrip has:</strong></p><ul><li>A stable architectural backbone</li><li>Domain-specific widgets</li><li>Controlled regeneration</li><li>A predictable interaction loop</li></ul><p>What remains are the questions every serious engineer eventually asks:</p><ul><li>How does this perform at scale?</li><li>How do we manage token usage?</li><li>What happens offline?</li><li>How do we fail gracefully?</li><li>Is this actually production-ready?</li></ul><p>These are not theoretical concerns.</p><h3>Part 8: Performance, Cost, and Latency — The Reality Check.</h3><p>When engineers talk about performance in Flutter apps, they usually mean frame times, rebuilds, and memory churn. In GenUI-based systems, performance has a <em>different shape</em>. The bottleneck is no longer rendering — Flutter is extremely good at that — but <strong>reasoning frequency</strong>.</p><p>Every time the UI meaningfully changes, the GenUI pipeline is activated. That pipeline includes serializing intent, sending it to a model, receiving structured output, validating it against schemas, and finally translating it into widgets.</p><p>Understanding <em>where</em> this pipeline is invoked — and where it should <strong>not</strong> be — is the first step toward making GenUI production-ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UyRiGs0FK6rs3GCFi6t_w.png" /></figure><h4>Where GenUI Is Actually Triggered (Code Reality)</h4><p>In your MyTrip implementation, GenUI is triggered in exactly <strong>two places</strong>:</p><ol><li>When the user submits free-form intent</li><li>When a GenUI widget emits an event</li></ol><p>This is intentional and visible in code.</p><p>Here is the <strong>single choke point</strong> where user intent enters the system:</p><pre>void sendUserMessage(String text) {<br>  conversation.sendRequest(<br>    UserMessage.text(text),<br>  );<br>}</pre><p>This function is deliberately boring. There is no preprocessing, no interpretation, no UI logic. The intent is passed <em>as-is </em>into the GenUiConversation.</p><p>Why does this matter?</p><p>Because performance optimizations start by <strong>limiting how often this function is called</strong>. If you accidentally trigger sendRequest on every keystroke, slider tick, or rebuild, you will destroy latency and cost predictability.</p><p>GenUI must be <strong>event-driven</strong>, not <strong>frame-driven</strong>.</p><h4>Event Emission: The Most Overlooked Performance Lever</h4><p>The real performance magic in GenUI happens <strong>after the first render</strong>, when users interact with widgets generated by the model.</p><p>Consider a budget slider.</p><p>In a naive implementation, you might emit events continuously as the slider moves. That would cause dozens of model calls for a single user gesture. Instead, GenUI widgets should emit <strong>semantic events</strong>, not raw UI signals. Here is an example of how a controlled event emission looks conceptually:</p><pre>GenUiSlider(<br>  value: budget,<br>  min: 50000,<br>  max: 150000,<br>  onChangedEnd: (newValue) {<br>    emitEvent(<br>      name: &#39;budget_changed&#39;,<br>      payload: {<br>        &#39;budget&#39;: newValue,<br>      },<br>    );<br>  },<br>);</pre><p>Notice what is <em>not</em> happening:</p><ul><li>No events during drag</li><li>No partial values</li><li>No UI noise</li></ul><p>The model receives <strong>one clear signal</strong>: the budget has changed.</p><p>This dramatically reduces:</p><ul><li>Token usage</li><li>Latency spikes</li><li>UI thrashing</li></ul><p>And it improves reasoning quality, because the model receives <strong>final intent</strong>, not intermediate noise.</p><h4>Surface-Level Regeneration (Code in Practice)</h4><p>One of the most important performance optimizations in MyTrip is something that doesn’t look like a performance optimization at all: <strong>surface isolation</strong>.</p><p>In the UI layer, surfaces are rendered independently:</p><pre>Column(<br>  children: [<br>    GenUiSurface(<br>      host: host,<br>      surfaceId: &#39;trip_overview&#39;,<br>    ),<br>    GenUiSurface(<br>      host: host,<br>      surfaceId: &#39;trip_controls&#39;,<br>    ),<br>    GenUiSurface(<br>      host: host,<br>      surfaceId: &#39;itinerary&#39;,<br>    ),<br>    GenUiSurface(<br>      host: host,<br>      surfaceId: &#39;options&#39;,<br>    ),<br>  ],<br>);</pre><p>What matters here is not the widget tree — it’s the <strong>surface IDs</strong>.</p><p>When the model responds to an event, it does <strong>not</strong> regenerate the entire UI. It only regenerates the surfaces affected by the event.</p><p>For example:</p><ul><li>A budget change updates itinerary and options</li><li>A preference toggle updates trip_controls and itinerary</li><li>The app shell remains untouched</li></ul><p>This keeps Flutter rebuilds cheap and localized, and it keeps GenUI’s reasoning scope small.</p><h4>Token Cost Control Starts in System Instructions</h4><p>Token usage is not primarily controlled by model choice. It is controlled by <strong>how much freedom you give the model to talk</strong>. Your system instruction should aggressively discourage prose.</p><p>Here is an excerpt-style instruction that works well for MyTrip:</p><pre>const travelSystemInstruction = &#39;&#39;&#39;<br>You are a travel planner UI agent.<br><br>Always respond using GenUI surfaces.<br>Do not include explanatory text.<br>Prefer structured UI components over paragraphs.<br>Regenerate only affected surfaces.<br>&#39;&#39;&#39;;</pre><p>This may feel restrictive — and that’s the point.</p><p>The model should not explain <em>why</em> it chose something. The UI already communicates that. Every unnecessary sentence is:</p><ul><li>Extra tokens</li><li>Extra latency</li><li>Extra cognitive load</li></ul><p>In GenUI, silence is a feature.</p><h3>Latency Perception vs Actual Latency</h3><p>An important psychological detail: users don’t experience latency uniformly. A 600ms response that updates <em>one section</em> of the screen feels faster than a 300ms response that redraws everything. By isolating regeneration to specific surfaces, MyTrip exploits this perception gap. The app feels responsive because:</p><ul><li>Parts of the UI remain stable</li><li>Changes appear targeted</li><li>The user’s mental model remains intac</li></ul><p>This is not accidental UX polish — it is a <strong>direct consequence of surface architecture</strong>.</p><h3>Part 9: Error Handling, Fallbacks, and Trust</h3><p>No AI-powered system is complete without a failure strategy. In fact, the moment you introduce AI into UI, error handling becomes <em>more important</em>, not less.</p><p>GenUI errors fall into three broad categories:</p><ol><li>Model errors (timeouts, quota issues)</li><li>Schema errors (invalid output)</li><li>UX errors (confusing or missing UI)</li></ol><p>Each must be handled differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gFKZYymy1voaergjnk5Tw.png" /></figure><h3>Handling Model Errors Without Breaking the App</h3><p>The most important rule: <strong>GenUI errors must never crash the UI</strong>.</p><p>In MyTrip, the conversation lifecycle is wrapped defensively:</p><pre>try {<br>  conversation.sendRequest(<br>    UserMessage.text(userInput),<br>  );<br>} catch (e) {<br>  showFallbackMessage(<br>    &#39;Unable to update plan right now. Please try again.&#39;,<br>  );<br>}</pre><p>This fallback is intentionally generic.</p><p>Why?<br>Because exposing model internals to users destroys trust. Users don’t care whether Gemini timed out or schema validation failed. They care whether the app remains usable.</p><h3>UI Fallbacks Instead of Error Screens</h3><p>One of the smartest GenUI patterns is to <strong>render fallback UI inside surfaces</strong>, rather than showing modal error dialogs.</p><p>For example, if itinerary generation fails, the itinerary surface can render a simple retry card:</p><pre>RetryCard(<br>  title: &#39;Could not update itinerary&#39;,<br>  onRetry: () {<br>    conversation.sendRequest(<br>      UserMessage.text(&#39;Retry itinerary generation&#39;),<br>    );<br>  },<br>);<br></pre><p>This keeps the interaction localized and prevents context loss. The rest of the UI remains intact.</p><h4>Trust Is Built Through Consistency, Not Accuracy.</h4><p>A subtle but critical insight: users will forgive <em>incorrect suggestions</em> far more readily than <em>inconsistent behavior</em>.</p><p>GenUI systems should therefore optimize for:</p><ul><li>Stable layouts</li><li>Predictable controls</li><li>Incremental updates</li></ul><p>Even if the itinerary isn’t perfect, the user trusts the app because:</p><ul><li>Controls behave consistently</li><li>Changes are reversible</li><li>The UI reflects their actions immediately</li></ul><p>This is why deterministic UI structure matters more than perfect AI output.</p><h4>The Hidden Advantage: Observability.</h4><p>Because GenUI interactions are structured, you can log them.</p><pre>void onGenUiEvent(GenUiEvent event) {<br>  logEvent(<br>    name: event.name,<br>    payload: event.payload,<br>  );<br>}</pre><p>This gives you:</p><ul><li>Clear analytics on user intent</li><li>Reproducible AI interactions</li><li>Insight into where users struggle</li></ul><p>Traditional chat UIs do not offer this clarity.</p><h3>Part 10: GenUI vs Traditional Flutter UI — A Concrete, Engineering Comparison.</h3><p>At this stage, it’s important to stop treating GenUI as an abstract idea and instead compare it head-to-head with how Flutter apps are traditionally built. Not philosophically, but mechanically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i810Sp7f3H3KTJuU-g_dFw.png" /></figure><p>In a conventional Flutter travel planner, UI structure is known at compile time. You create screens, routes, and flows that assume a certain order of operations: first collect destination, then dates, then budget, then preferences. Even if you collapse everything into a single screen, the widget tree still encodes a fixed worldview.</p><p>Consider a simplified traditional approach:</p><pre>class TravelPlannerForm extends StatefulWidget {<br>  @override<br>  State&lt;TravelPlannerForm&gt; createState() =&gt; _TravelPlannerFormState();<br>}<br><br>class _TravelPlannerFormState extends State&lt;TravelPlannerForm&gt; {<br>  String destination = &#39;&#39;;<br>  int days = 3;<br>  int budget = 100000;<br>  bool withKids = false;<br>  bool prefersIndoor = false;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Plan your trip&#39;)),<br>      body: ListView(<br>        padding: const EdgeInsets.all(16),<br>        children: [<br>          TextField(<br>            decoration: const InputDecoration(labelText: &#39;Destination&#39;),<br>            onChanged: (v) =&gt; setState(() =&gt; destination = v),<br>          ),<br>          DropdownButtonFormField&lt;int&gt;(<br>            value: days,<br>            items: [3, 4, 5, 7]<br>                .map((d) =&gt; DropdownMenuItem(<br>                      value: d,<br>                      child: Text(&#39;$d days&#39;),<br>                    ))<br>                .toList(),<br>            onChanged: (v) =&gt; setState(() =&gt; days = v ?? days),<br>          ),<br>          Slider(<br>            value: budget.toDouble(),<br>            min: 50000,<br>            max: 150000,<br>            onChanged: (v) =&gt; setState(() =&gt; budget = v.round()),<br>          ),<br>          SwitchListTile(<br>            title: const Text(&#39;Traveling with kids&#39;),<br>            value: withKids,<br>            onChanged: (v) =&gt; setState(() =&gt; withKids = v),<br>          ),<br>          SwitchListTile(<br>            title: const Text(&#39;Prefer indoor activities&#39;),<br>            value: prefersIndoor,<br>            onChanged: (v) =&gt; setState(() =&gt; prefersIndoor = v),<br>          ),<br>          ElevatedButton(<br>            onPressed: generateItinerary,<br>            child: const Text(&#39;Generate itinerary&#39;),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>This works — but it encodes several assumptions:</p><ul><li>The user knows all inputs upfront</li><li>The flow is linear</li><li>Changes require rebuilding logic paths</li><li>UI and intent are tightly coupled</li></ul><p>Now compare that with the <strong>GenUI approach</strong> in MyTrip. The Flutter UI itself barely changes:</p><pre>class PlannerScreen extends StatelessWidget {<br>  final GenUiConversation conversation;<br><br>  const PlannerScreen({required this.conversation});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;MyTrip&#39;)),<br>      body: Column(<br>        children: [<br>          Expanded(<br>            child: ListView(<br>              padding: const EdgeInsets.all(16),<br>              children: const [<br>                GenUiSurface(surfaceId: &#39;trip_overview&#39;),<br>                GenUiSurface(surfaceId: &#39;trip_controls&#39;),<br>                GenUiSurface(surfaceId: &#39;itinerary&#39;),<br>                GenUiSurface(surfaceId: &#39;options&#39;),<br>              ],<br>            ),<br>          ),<br>          MessageInputBar(<br>            onSend: (text) {<br>              conversation.sendRequest(UserMessage.text(text));<br>            },<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>The <em>meaning</em> of the UI lives elsewhere:</p><ul><li>In the catalog</li><li>In the system instruction</li><li>In the conversation state</li></ul><p>This decoupling is the key difference.</p><p>In traditional Flutter:</p><blockquote><em>UI structure → dictates intent</em></blockquote><p>In GenUI:</p><blockquote><em>Intent → produces UI structure</em></blockquote><p>Once you internalize this inversion, GenUI stops feeling strange and starts feeling inevitable.</p><h3>Part 11: Beyond Travel — Where GenUI Actually Makes Sense</h3><p>Travel planning is a strong demonstration, but GenUI is not a “travel feature.” It’s a <strong>pattern</strong>, and like all good patterns, it applies selectively.</p><p>GenUI excels in domains where:</p><ul><li>User intent is incomplete or evolving</li><li>Inputs are interdependent</li><li>The UI benefits from gradual disclosure</li><li>The user prefers refinement over navigation</li></ul><p>Let’s look at a few concrete examples.</p><h3>Task Management (Intent-First, Not Form-First)</h3><p>A traditional task app asks:</p><ul><li>Title</li><li>Date</li><li>Priority</li><li>Tags</li><li>Notes</li></ul><p>A GenUI task system starts with:</p><blockquote><em>“I need to prepare for a Flutter conference talk next week.</em></blockquote><p>The UI might <em>generate</em>:</p><ul><li>A task cluster</li><li>Suggested subtasks</li><li>A timeline slider</li><li>Focus category chips</li></ul><p>As the user interacts, the UI refines the task — without ever forcing a rigid form.</p><p>The underlying code remains almost identical to MyTrip:</p><ul><li>Different catalog</li><li>Different system instruction</li><li>Same surfaces and conversation loop.</li></ul><h4>When <em>Not</em> to Use GenUI</h4><p>A responsible technical article must say this clearly:</p><p><strong>GenUI is not a universal solution.</strong></p><p>There are entire classes of UI where GenUI is the wrong tool.</p><h3>Bad Fits for GenUI</h3><p>GenUI should not be used for:</p><ul><li>Settings screens</li><li>Authentication flows</li><li>Compliance-heavy forms</li><li>Financial transaction confirmations</li><li>Highly regulated workflows</li></ul><p>These screens benefit from:</p><ul><li>Predictability</li><li>Explicit validation</li><li>Deterministic structure</li><li>Legal clarity</li></ul><p>Using AI here adds risk without value.</p><h4>Security and Data Considerations.</h4><p>From a security standpoint, GenUI does not introduce new categories of risk — but it <strong>amplifies existing ones</strong> if handled carelessly.</p><p>Best practices from MyTrip:</p><ul><li>Never send PII unnecessarily</li><li>Never embed secrets in prompts</li><li>Treat model responses as untrusted input</li><li>Validate schemas strictly</li><li>Keep catalogs minimal</li></ul><p>Flutter remains responsible for rendering safety.<br>AI never bypasses Flutter’s type system.</p><h4>Production Checklist (Code-Driven)</h4><p>Before shipping a GenUI feature, the MyTrip approach implicitly enforces:</p><pre>assert(catalog.items.isNotEmpty);<br>assert(surfaceIds.toSet().length == surfaceIds.length);<br>assert(systemInstruction.isNotEmpty);</pre><p>And at runtime:</p><ul><li>Event logging</li><li>Error capture</li><li>Retry paths</li><li>Surface stability</li></ul><p>GenUI is only risky when it is vague. Clear constraints make it boring — and boring is good.</p><h3>Conclusion: What GenUI Really Changes for Flutter Engineers.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9SbIaANCPYZMk6SaFMOiA.png" /></figure><p>Flutter GenUI is not about letting AI design your app. It is about recognizing that <strong>intent is dynamic</strong>, while <strong>UI systems are static</strong> — and bridging that gap responsibly.</p><p>GenUI introduces a new design discipline:</p><ul><li>You design <em>capabilities</em>, not screens</li><li>You define <em>constraints</em>, not flows</li><li>You teach the system how to think in UI terms</li></ul><p>Flutter remains the rendering engine.<br>Flutter remains deterministic.<br>Flutter remains in control.</p><p>GenUI simply decides <strong>which parts of your system matter right now</strong>.</p><p>If you want to check in the integration of the GenUI in Flutter app, check the <a href="https://github.com/ShreeBhagwat/genui_onboarding_clean">GitRepo</a> .</p><h3>Closing Thoughts</h3><p>Flutter GenUI represents a meaningful shift in how we think about user interfaces — not as fixed structures we must fully anticipate, but as living systems that evolve alongside user intent. By combining Flutter’s deterministic rendering model with a constrained, schema-driven generative layer, GenUI allows us to build interfaces that are adaptive without being chaotic, dynamic without being unpredictable. This is not “AI designing UI for us”; it is engineers designing the rules under which UI can responsibly emerge.</p><p>The MyTrip travel planner demonstrates what becomes possible when intent, interaction, and structure are treated as first-class citizens. Instead of forcing users through rigid forms or burying state inside chat transcripts, the UI itself becomes a shared workspace between the user and the system — one that can be refined, adjusted, and trusted. Crucially, Flutter remains firmly in control: widgets are still widgets, layout is still deterministic, and performance characteristics are still knowable. GenUI doesn’t replace Flutter’s strengths; it amplifies them.</p><p>As engineers, this challenges us to think differently about our role. We move from designing screens to designing vocabularies, from wiring flows to defining constraints, and from anticipating every edge case to building systems that can adapt safely. GenUI is not the future of all UI — but for domains driven by exploration, ambiguity, and evolving intent, it is a powerful new tool. Used with discipline, it allows us to build software that feels less like a form to be filled and more like a conversation that understands.</p><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*SeeEuuv7zhBbCdu6.gif" /></figure><figure><a href="http://buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/0*6zK-aQWQS5hQy-uF.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bb41f26e0d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Custom SMS Authentication in Supabase Using SMS Hook and MSG91]]></title>
            <link>https://medium.com/@shreebhagwat94/implementing-custom-sms-authentication-in-supabase-using-sms-hook-and-msg91-366d13acc81c?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/366d13acc81c</guid>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 20:28:14 GMT</pubDate>
            <atom:updated>2025-12-19T20:28:14.667Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Extending Supabase phone authentication with a custom SMS provider using Auth Hooks</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeWFGnwvmlWRVN8QJGEXGw.png" /></figure><p>I’ve been working on a <strong>Flutter + AI project</strong> where <strong>Supabase</strong> powers the backend. One of the first requirements was implementing <strong>phone-based authentication</strong> for user login — a fairly standard feature, but one that quickly revealed a practical challenge.</p><p>Supabase supports <strong>Twilio</strong> as the default SMS provider. While it works well globally, it isn’t the most <strong>cost-effective option for India</strong>, especially when OTP traffic starts scaling. In contrast, Indian SMS providers like <strong>MSG91</strong> offer significantly better pricing and local compliance, making them a much more practical choice.</p><p>Naturally, I wanted to integrate <strong>MSG91 with Supabase Auth</strong>. Supabase does provide an <strong>SMS Hook</strong>, which theoretically allows you to plug in any custom SMS provider. However, when I started looking for examples or guides specifically for <strong>MSG91</strong>, I found… nothing. No complete walkthroughs, no real-world implementations — just scattered hints.</p><p>After spending time experimenting, reading Supabase internals, and wiring everything together myself, I finally got it working.</p><p>This blog exists for two reasons:</p><ol><li>So <strong>you don’t have to struggle</strong> the same way I did.</li><li>So <strong>future me doesn’t forget</strong> how this was done the next time I need it.</li></ol><p>If you’re building for India and want <strong>full control over OTP delivery using Supabase</strong>, this guide will walk you through exactly how to do it.</p><h3>What are we going to cover</h3><ul><li>Introduction to Supabase Phone Authentication</li><li>What is Supabase SMS Hook and when it is triggered</li><li>Understanding Supabase Auth Hooks at a high level</li><li>High-level architecture of Supabase + SMS Hook + MSG91</li><li>Enabling and configuring SMS Hook in Supabase</li><li>Creating a Supabase Edge Function for SMS handling</li><li>Verifying Supabase webhook signatures</li><li>Extracting OTP and phone number from hook payload</li><li>Using MSG91 SMS API to send OTP messages</li><li>Managing environment variables and secrets securely</li><li>Deploying the Edge Function</li><li>Connecting the Edge Function to Supabase SMS Hook</li><li>Handling errors and SMS delivery failures</li></ul><h3>Introduction to Supabase</h3><p><a href="https://supabase.com/">Supabase</a> is an <strong>open-source backend-as-a-service (BaaS)</strong> that provides developers with a powerful alternative to traditional custom backends. Built on top of <strong>PostgreSQL</strong>, Supabase offers essential backend features such as authentication, real-time subscriptions, storage, edge functions, and row-level security — all exposed through simple APIs. For frontend developers working with frameworks like <strong>Flutter</strong>, Supabase significantly reduces backend complexity while still offering full control and transparency.</p><p>One of Supabase’s biggest strengths is its <strong>developer-first approach</strong>. Instead of abstracting everything behind proprietary layers, Supabase exposes raw PostgreSQL, making it easy to reason about data, security policies, and performance. This makes it especially appealing for startups and indie developers who want to move fast without sacrificing scalability or correctness.</p><h3>Introduction to Supabase Phone Authentication</h3><p>Supabase includes built-in <strong>authentication services</strong> that support email/password, OAuth providers, magic links, and <strong>phone number authentication using OTP (One Time Password)</strong>. Phone authentication is particularly popular in mobile applications, where users expect quick, passwordless login experiences. Supabase handles OTP generation, verification, session creation, and token management, allowing developers to focus on the app experience rather than authentication logic.</p><h3>What Is Supabase SMS Hook and When Is It Triggered?</h3><p>Supabase <strong>SMS Hook</strong> is part of Supabase Auth Hooks, a feature that allows developers to <strong>intercept and customize the authentication flow</strong>. Specifically, the <strong>Send SMS Hook</strong> is triggered whenever Supabase needs to send an SMS message as part of phone-based authentication. Instead of Supabase directly sending the SMS via its default provider, the hook gives developers the opportunity to route the message through a <strong>custom SMS service</strong> of their choice.</p><p>The SMS Hook is triggered <strong>before</strong> the OTP message is sent to the user. Supabase generates the OTP internally and then sends a secure webhook request containing the OTP, the user’s phone number, and related metadata to the configured hook endpoint. This endpoint is typically a <strong>Supabase Edge Function</strong>, which verifies the request, formats the SMS message, and forwards it to an external SMS provider such as MSG91. Supabase still remains responsible for OTP validation and session management — only the delivery mechanism is customized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOnEG5ZfxD8JDPeNHn09ag.png" /></figure><h3>Understanding Supabase Auth Hooks at a High Level</h3><p>At a high level, Auth Hooks work through <strong>secure webhooks</strong>. When a particular authentication event occurs, Supabase sends a signed HTTP request containing relevant data (such as user information or OTP details) to a developer-defined endpoint. This endpoint is usually implemented as a <strong>Supabase Edge Function</strong>, which processes the request and performs the required action. The webhook signature ensures that the request is genuinely coming from Supabase and hasn’t been tampered with.</p><h3>Overview of MSG91 as an Indian SMS Provider</h3><p><strong>MSG91</strong> is a widely used Indian cloud communication platform that provides APIs for sending OTPs, transactional SMS, and alerts, making it a strong alternative to global providers for applications targeting Indian users. It offers <strong>cost-effective pricing</strong>, reliable delivery within India, and built-in support for <strong>DLT compliance</strong>, which is mandatory for sending SMS in the Indian telecom ecosystem. With simple REST APIs and support for sender IDs and templates, MSG91 is well suited for integrating custom OTP delivery flows — such as Supabase SMS Hooks — while maintaining regulatory compliance and reducing operational costs.</p><h3>Supabase Setup — Enabling SMS-Hook</h3><h4><strong>1. Access the Hooks Dashboard</strong></h4><p>https://supabase.com/dashboard/project/_/auth/hooks.</p><p>don’t forget to add your project key after project/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWJh2tByW7Eh31ReshibhQ.png" /><figcaption>Supabase place to access Auth Hooks</figcaption></figure><p>Initiate SMS — Hook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*Rc2dS5Zg6b9s_U1jqWgU8A.png" /></figure><ul><li>Toggle on Enable Send SMS Hook.</li><li>Make sure to select HTTPS as Hook Type.</li><li>Pass the URL endpoint<br>https://{supabase_project_id}.supabase.co/functions/v1/sms-hook<br><em>This enpoint is the sms-hook edge function that we are going create later on . So if you change the edge function name, make sure you update the URL end point.</em></li><li>Generate and Save the Secret.</li></ul><h3>Implementing the SMS Hook Edge Function in Supabase</h3><p>Once the custom SMS hook is enabled in Supabase, we need an <strong>Edge Function</strong> to process incoming webhook requests and send OTP messages using our SMS provider. This function acts as the bridge between Supabase Auth and MSG91. The following steps walk through the implementation of the sms-hook Edge Function.</p><h3>Prerequisites</h3><p>Before you begin, ensure the following tools are installed and configured on your machine:</p><ul><li><strong>Supabase CLI</strong> — required to create, deploy, and manage Edge Functions</li><li><strong>Docker Desktop</strong> — used by the Supabase CLI for local function builds and testing</li><li>An active <strong>Supabase project</strong> with Auth enabled</li></ul><h4>Creating Edge Functions</h4><ul><li>Authenticate with Supabase CLI — Log in to your Supabase account using the CLI. This will open a browser window for authentication.</li></ul><pre>npx supabase login</pre><ul><li>List your Supabase projects — Once authenticated, list all Supabase projects associated with your account.</li></ul><pre>npx supabase projects list</pre><ul><li>Link Your Local Directory to the Supabase Project — Link your local workspace to the selected Supabase project using its reference ID.</li></ul><pre>npx supabase link --project-ref &lt;your-project-id&gt;</pre><ul><li>Create the SMS Hook Edge Function — Create a new Edge Function named sms-hook. This function will be responsible for receiving OTP payloads from Supabase and sending SMS messages via MSG91.</li></ul><pre>npx supabase functions new sms-hook</pre><h3><strong>Implement the SMS Sending Edge Function Logic</strong></h3><h4>1. Extracting OTP and Phone Number from Hook Payload</h4><p>When Supabase triggers the <strong>Send SMS Hook</strong>, it sends a signed webhook payload containing the OTP and user details. The first step is to <strong>verify the webhook</strong> and safely extract the required fields.</p><pre>import { Webhook } from &quot;https://esm.sh/standardwebhooks@1.0.0&quot;;<br><br>type HookPayload = {<br>  user?: { phone?: string };<br>  sms?: { otp?: string };<br>};</pre><p>Inside the Edge Function, the payload is verified using Supabase’s webhook secret. Once verified, we can safely access the phone number and OTP generated by Supabase.</p><pre>const payload = await req.text();<br>const headers = Object.fromEntries(req.headers);<br><br>const wh = new Webhook(SUPABASE_WEBHOOK_SECRET_BASE64);<br>const { user, sms } = wh.verify(payload, headers);<br><br>const phone = user?.phone ?? &quot;&quot;;<br>const otp = sms?.otp ?? &quot;&quot;;</pre><p>At this point:</p><ul><li><strong>Supabase owns OTP generation and validation</strong></li><li>Your Edge Function only handles <strong>delivery.</strong></li></ul><h4>2. Normalizing Phone Numbers (E.164 Format)</h4><p>MSG91 requires phone numbers in <strong>E.164 format</strong> (+91xxxxxxxxxx). Since user input may vary, normalization is essential.</p><pre>function normalizeToE164(phoneNumber: string): string {<br>  let cleaned = phoneNumber.replace(/[^\d+]/g, &quot;&quot;);<br><br>  if (!cleaned.startsWith(&quot;+&quot;)) {<br>    const digitsOnly = cleaned.replace(/\+/g, &quot;&quot;);<br><br>    if (digitsOnly.length === 10) return `+91${digitsOnly}`;<br>    if (digitsOnly.length === 12 &amp;&amp; digitsOnly.startsWith(&quot;91&quot;)) return `+${digitsOnly}`;<br>    if (digitsOnly.length === 11 &amp;&amp; digitsOnly.startsWith(&quot;0&quot;)) return `+91${digitsOnly.substring(1)}`;<br>  }<br><br>  return cleaned;<br>}</pre><p>This ensures consistent routing, pricing, and delivery across all Indian carriers.</p><h4>3. Blocking Test Phone Numbers (Optional but Recommended)</h4><p>To avoid unnecessary SMS usage during testing, specific phone numbers can be blocked.</p><pre>const TEST_PHONE_NUMBERS = [<br>  &quot;919999999999&quot;,<br>  &quot;919999999998&quot;,<br>  &quot;918888888888&quot;,<br>];<br><br>function isTestPhoneNumber(phoneNumber: string): boolean {<br>  const digitsOnly = phoneNumber.replace(/[^\d]/g, &quot;&quot;);<br>  return TEST_PHONE_NUMBERS.some(test =&gt;<br>    digitsOnly.endsWith(test)<br>  );<br>}</pre><pre>const e164Phone = normalizeToE164(phone);<br><br>if (isTestPhoneNumber(e164Phone)) {<br>  return new Response(<br>    JSON.stringify({ message: &quot;SMS blocked for test number&quot; }),<br>    { status: 200 }<br>  );<br>}</pre><p>This is extremely useful in staging and QA environments.</p><h4>4. Using MSG91 SMS API to Send OTP Messages</h4><p><em>Make sure MSG91 dashboard is done and message is approved by DLT.</em></p><p>MSG91 uses a <strong>Flow-based API</strong>, where message templates are pre-approved and variables (like OTP) are injected dynamically.</p><pre>const MSG91_API_URL = &quot;https://control.msg91.com/api/v5/flow&quot;;<br><br>async function sendViaMSG91(otp: string, toNumber: string) {<br>  const payload = {<br>    template_id: MSG91_FLOW_ID,<br>    short_url: &quot;0&quot;, // 0 means no URL in sms, 1 means there is short url. We passs 0 here<br>    recipients: [<br>      {<br>        mobiles: toNumber, // Phone number where we want to send SMS<br>        otp: otp, // DTL approved Variable 1<br>        app: &quot;App_Name&quot; // DLT approved Varibale 2<br>      }<br>    ]<br>  };<br><br>  return fetch(MSG91_API_URL, { <br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      authkey: MSG91_AUTHKEY, // you will get this Auth key MSG91 dashboard<br>    },<br>    body: JSON.stringify(payload),<br>  });<br>}</pre><p>MSG91 handles:</p><ul><li>DLT compliance</li><li>Template validation</li><li>SMS routing</li></ul><p>Supabase remains unaware of the provider swap.</p><h4>5. Managing Environment Variables and Secrets Securely</h4><p>All sensitive values are stored as <strong>environment variables</strong>, never hardcoded in logic.</p><pre>const SUPABASE_WEBHOOK_SECRET_BASE64 = Deno.env.get(&quot;SUPABASE_WEBHOOK_SECRET&quot;)!;<br>const MSG91_AUTHKEY = Deno.env.get(&quot;MSG91_AUTHKEY&quot;)!;<br>const MSG91_FLOW_ID = Deno.env.get(&quot;MSG91_FLOW_ID&quot;)!;</pre><ul><li>Easy key rotation</li><li>Separate configs for dev/staging/prod</li><li>Zero secret leakage in Git repos</li></ul><h4>6. Handling Errors and SMS Delivery Failures</h4><p>SMS delivery failures are handled gracefully without breaking authentication.</p><pre>const response = await sendViaMSG91(otp, e164Phone);<br><br>if (response.status !== 200) {<br>  return new Response(<br>    JSON.stringify({<br>      error: {<br>        http_code: response.status,<br>        message: await response.text(),<br>      },<br>    }),<br>    { status: response.status }<br>  );<br>}</pre><p>Webhook verification errors, stale timestamps, and signature mismatches are also caught early and rejected securely.</p><h4>7. Deploying the Edge Function</h4><p>The Edge Function is deployed using the Supabase CLI. Since this endpoint is triggered internally by Supabase, JWT verification is disabled.</p><pre>supabase functions deploy sms-hook --no-verify-jwt</pre><p><em>Note — make sure the edge function deployed, JWT verification is disabled. If not the edge function running will fail.</em></p><p>After deployment, Supabase generates a public HTTPS endpoint for the function.</p><h4><strong>8. Enable Phone Authentication</strong></h4><p>Remember to enable the phone provider from Authentication Providers in your Supabase Dashboard as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SDiP2EVOmW4re9qpGMCySQ.png" /></figure><h3>Flutter + Supabase Setup</h3><p>Add supabase Flutter package to pubspec.yaml</p><pre>dart pub add supabase_flutter</pre><p>Add send OTP function</p><pre>  Future&lt;void&gt; sendOTP(String phoneNumber) async {<br>    try {<br>      log(&#39;Sending OTP to phone: $phoneNumber&#39;, name: &#39;PhoneAuthService&#39;);<br><br>      log(&#39;Using redirect URL: $redirectUrl&#39;, name: &#39;PhoneAuthService&#39;);<br>      <br>      await SupabaseService.client.auth.signInWithOtp(<br>        phone: phoneNumber,<br>        channel: OtpChannel.sms,<br>      );<br>      <br>      log(&#39;OTP sent successfully to: $phoneNumber&#39;, name: &#39;PhoneAuthService&#39;);<br>    } catch (e) {<br>      log(&#39;Error sending OTP: $e&#39;, name: &#39;PhoneAuthService&#39;);<br>      throw _handleAuthError(e);<br>    }<br>  }</pre><p>This function initiates <strong>phone number authentication using OTP (One Time Password)</strong> through Supabase. When called, it requests Supabase to generate an OTP and send it to the provided phone number via SMS.</p><p>Here’s what happens step by step:</p><ol><li>The function receives a <strong>phone number</strong> from the user.</li><li>It logs diagnostic messages to help with debugging and monitoring.</li><li>It calls Supabase’s signInWithOtp method, specifying:</li></ol><ul><li>The phone number to authenticate</li><li>The SMS channel for OTP delivery</li></ul><p>4. Supabase generates an OTP and triggers the configured <strong>SMS delivery mechanism</strong> (default provider or your custom SMS hook).</p><p>5. If the request succeeds, the OTP is sent to the user’s phone.</p><p>6. If anything goes wrong, the error is caught, logged, and converted into a user-friendly authentication error.</p><h4>Verify the OTP Function</h4><pre> Future&lt;AuthResponse&gt; verifyOTP(String phoneNumber, String otp) async {<br>    try {<br>      log(&#39;Verifying OTP for phone: $phoneNumber&#39;, name: &#39;PhoneAuthService&#39;);<br><br>      final response = await SupabaseService.client.auth.verifyOTP(<br>        phone: phoneNumber,<br>        token: otp,<br>        type: OtpType.sms,<br>      );<br>      <br>      if (response.session?.user != null) {<br>        log(&#39;OTP verified successfully for user: ${response.session!.user.id}&#39;, name: &#39;PhoneAuthService&#39;);<br>      } else {<br>        log(&#39;OTP verification failed: No session returned&#39;, name: &#39;PhoneAuthService&#39;);<br>        throw Exception(&#39;OTP verification failed: No user session created&#39;);<br>      }<br>      <br>      return response;<br>    } catch (e) {<br>      log(&#39;Error verifying OTP: $e&#39;, name: &#39;PhoneAuthService&#39;);<br>      throw _handleAuthError(e);<br>    }<br>  }</pre><p>This function <strong>verifies the OTP (One Time Password)</strong> entered by the user and completes the phone-based authentication flow using Supabase. While the previous function triggers OTP generation and delivery, this function is responsible for <strong>validating the OTP and creating a user session</strong>.</p><ul><li>The function receives the <strong>phone number</strong> and the <strong>OTP</strong> entered by the user.</li><li>It logs the verification attempt for debugging and traceability.</li><li>It calls Supabase’s verifyOTP API, passing:<br> — The phone number<br> — The OTP token provided by the user</li><li>The OTP type (OtpType.sms)</li><li>Supabase validates the OTP against the one it previously generated.</li><li>If the OTP is valid: <br>— Supabase creates an authenticated session <br>— A user object is attached to the session</li><li>The function checks whether a valid session and user were returned.</li><li>If successful, it logs the authenticated user ID and returns the full AuthResponse.</li><li>If verification fails or no session is created, an error is thrown and handled gracefull</li></ul><h3>Conclusion</h3><p>Supabase makes phone-based authentication simple and secure, but real-world applications often demand more control — especially when it comes to <strong>SMS delivery, regional compliance, and cost optimization</strong>. By leveraging <strong>Supabase SMS Hooks</strong> and <strong>Edge Functions</strong>, you can replace the default SMS provider without touching the core authentication logic, while still benefiting from Supabase’s robust OTP generation and verification.</p><p>Integrating <strong>MSG91</strong> demonstrates how flexible this approach can be for Indian applications. You retain full ownership over SMS templates, pricing, and DLT compliance, while Supabase continues to handle sessions, users, and security. This separation of responsibilities keeps your architecture clean, scalable, and production-ready.</p><p>Most importantly, this setup turns what initially feels like a limitation into a powerful extension point. Whether you’re building with Flutter or any other frontend, this pattern ensures your authentication flow is both <strong>developer-friendly and region-optimized</strong>. If you’re targeting India — or any region where local SMS providers make more sense — custom SMS hooks are not just an option, they’re the right architectural choice.</p><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Q6NW0VDfM1euwP7W16vK_A.gif" /></figure><figure><a href="https://buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/1*DUreAUtI7Mxkg9RjzUiyvQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366d13acc81c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing a Flutter App That Doesn’t Feel Like an iOS App]]></title>
            <link>https://medium.com/@shreebhagwat94/fixing-a-flutter-app-that-doesnt-feel-like-an-ios-app-507c4d3b8dfb?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/507c4d3b8dfb</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 17:43:39 GMT</pubDate>
            <atom:updated>2025-12-19T17:43:39.144Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A Practical Guide to High iOS Fidelity with Flutter</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51kF15b54RPg_su6YP-LQQ.png" /></figure><p>I’ve shipped multiple Flutter apps to the App Store that were technically correct in every way.</p><ul><li>They passed review.</li><li>They were smooth and fast.</li><li>They had no obvious bugs.</li></ul><p>And yet, I used to always feel the same way:</p><blockquote>“It works… but it doesn’t feel like an iOS app.”</blockquote><ul><li>Not broken.</li><li>Not wrong.</li><li>Just <em>off</em>.</li></ul><h3>Background</h3><p>Before Flutter, I was an iOS developer.</p><p>I built multiple native iOS apps using UIKit and later SwiftUI. I lived inside Xcode, fought Auto Layout, obsessed over scroll performance, and learned — sometimes the hard way — why iOS users notice the smallest inconsistencies. I didn’t just <em>use</em> iOS; I internalised how it behaves.</p><p>When I first tried flutter I was skeptical about it. I felt the same thing, <em>it doesn’t feel like an iOS app. </em>But I thought this feeling will go away as Flutter is new and when it matures this issues will be fixed.</p><p>Cut Short to today — That feeling is still there, when I use the flutter app that I have built for clients. I become uncomfortable — because I knew what “iOS-like” actually meant. Flutter wasn’t the problem. The problem was that we were building <strong>platform-agnostic experiences on a platform that has a very strong personality</strong>.</p><p>On iOS, users don’t judge apps by <strong>features or frameworks</strong>. They judge them by feel. The way navigation behaves without explanation. The way gestures respond without thought. The way text, motion, and spacing quietly follow expectations built over years of using Apple’s apps.</p><p><em>This article is about fixing that gap.</em></p><p>Not by forcing Flutter to imitate iOS, but by applying iOS-native thinking to Flutter development. We’ll take a Flutter app that technically works but doesn’t feel native on iOS, break down exactly why it feels wrong, and fix it using concrete design decisions, platform-aware architecture, and real Flutter code.</p><p>If you’ve ever built native iOS apps — and now build with Flutter — or if you’ve shipped a Flutter app that users said felt “almost right,” this guide is for you.</p><h3>This blog is about fixing that — <strong>technically</strong>.</h3><p>Not with opinions.<br>Not with Cupertino buzzwords.<br>But with <strong>real Flutter code</strong>, <strong>real decisions</strong>, and <strong>real trade-offs.</strong></p><h3>What “High iOS Fidelity” Means in Flutter Terms</h3><p>In Flutter, high iOS fidelity means:</p><ul><li>Using <strong>iOS mental models</strong>, not Android defaults</li><li>Respecting <strong>iOS navigation &amp; gestures</strong></li><li>Matching <strong>motion, typography, spacing</strong></li><li>Treating <strong>performance as UX</strong></li><li>Letting iOS conventions lead — Flutter follows</li></ul><p>Flutter gives you the power to do <em>anything</em>.<br>High fidelity is about knowing <strong>what <em>not</em> to do</strong>.</p><h4>1. Start With the Right App Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdSApVP1PQvl-mwLVQ6WPw.png" /></figure><p>❌ <strong><em>The Common Mistake</em></strong></p><pre>MaterialApp(<br>  home: HomeScreen(),<br>);</pre><p>This instantly biases your app toward Material behavior:</p><ul><li>Material page transitions</li><li>Android scroll physics</li><li>Android visual density</li></ul><p>Even if you later add Cupertino widgets, the foundation is wrong.</p><p>✅ <strong><em>iOS-First Flutter Setup</em></strong></p><pre>CupertinoApp(<br>  debugShowCheckedModeBanner: false,<br>  theme: CupertinoThemeData(<br>    brightness: Brightness.light,<br>  ),<br>  home: const HomeScreen(),<br>);</pre><p>✅ <strong><em>Or — if you need Material for shared components:</em></strong></p><pre>MaterialApp(<br>  theme: ThemeData(<br>    platform: TargetPlatform.iOS,<br>    useMaterial3: false,<br>  ),<br>  home: const HomeScreen(),<br>);</pre><h4>** Rule **</h4><blockquote>Start iOS-first, then add cross-platform flexibility — never the other way around.</blockquote><h4>2. Navigation: Respect the iOS Stack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pCjEntNC5cL9xeJgp3ZQA.png" /></figure><p>❌ <strong><em>Anti-Pattern</em></strong></p><ul><li>Nested navigators</li><li>Custom back buttons</li><li>Disabling swipe-back</li><li>Using pushReplacement everywhere</li></ul><p>These instantly break iOS trust.</p><p>✅ <strong><em>Cupertino Navigation (Correct Way)</em></strong></p><pre>CupertinoPageScaffold(<br>  navigationBar: CupertinoNavigationBar(<br>    middle: Text(&#39;Details&#39;),<br>  ),<br>  child: SafeArea(<br>    child: ContentView(),<br>  ),<br>);</pre><p>✅ <strong><em>Navigation push:</em></strong></p><pre>Navigator.of(context).push(<br>  CupertinoPageRoute(<br>    builder: (_) =&gt; DetailsScreen(),<br>  ),<br>);</pre><p>✔ Swipe-back works<br>✔ Title animates correctly<br>✔ Transitions feel native</p><h4><strong>3. Typography: Let iOS Control the Text</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72yEACFCiJYaln0Gnw1ezA.png" /></figure><p>❌ <strong><em>Hardcoded Fonts (Low Fidelity)</em></strong></p><pre>Text(<br>  &#39;Welcome&#39;,<br>  style: TextStyle(<br>    fontSize: 20,<br>    fontWeight: FontWeight.bold,<br>  ),<br>);</pre><p>This breaks:</p><ul><li>Dynamic Type</li><li>Accessibility</li><li>Layout scaling</li></ul><p>✅ <strong><em>Semantic iOS Typography in Flutter</em></strong></p><pre>Text(<br>  &#39;Welcome&#39;,<br>  style: CupertinoTheme.of(context)<br>      .textTheme<br>      .navLargeTitleTextStyle,<br>);</pre><p>✅ <strong><em>Or for adaptive text:</em></strong></p><pre>Text(<br>  &#39;Description&#39;,<br>  style: CupertinoTheme.of(context)<br>      .textTheme<br>      .textStyle,<br>);</pre><h4>** Rule **</h4><blockquote>On iOS, typography is not design — it’s infrastructure.</blockquote><h4>4. Spacing &amp; Density: Stop Over-Designing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjYe_KxAvApRbwW4_Hjl6w.png" /></figure><p>iOS apps breathe.<br>Flutter apps often suffocate.</p><p>❌ <strong><em>Typical Flutter Layout</em></strong></p><pre>Padding(<br>  padding: const EdgeInsets.all(8),<br>  child: Column(<br>    children: [...],<br>  ),<br>);</pre><p><strong>Too dense * Too symmetrical * Too Android.</strong></p><p>✅ <strong><em>iOS-Style Spacing</em></strong></p><pre>Padding(<br>  padding: const EdgeInsets.symmetric(<br>    horizontal: 16,<br>    vertical: 12,<br>  ),<br>  child: Column(<br>    crossAxisAlignment: CrossAxisAlignment.start,<br>    children: [...],<br>  ),<br>);</pre><h4>** Rule **</h4><blockquote>More vertical spacing | Fewer dividers | Clear hierarchy</blockquote><h4>5. Lists: Don’t Fight Them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmjIC0SomFszVchooTJ5Aw.png" /></figure><p>❌ <strong><em>Over-Custom Lists</em></strong></p><ul><li>Cards inside lists</li><li>Nested scroll views</li><li>Custom physics</li><li>Decorative separators</li></ul><p>✅ <strong><em>iOS-Native Lists in Flutter</em></strong></p><pre>CupertinoListSection.insetGrouped(<br>  children: [<br>    CupertinoListTile(<br>      title: Text(&#39;Profile&#39;),<br>      trailing: CupertinoListTileChevron(),<br>    ),<br>    CupertinoListTile(<br>      title: Text(&#39;Settings&#39;),<br>      trailing: CupertinoListTileChevron(),<br>    ),<br>  ],<br>);</pre><p>✔ Native scrolling<br>✔ Correct separators<br>✔ Automatic grouping</p><h4>6. Gestures: Never Break Muscle Memory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3d4SjghTLk5RV7TbKytDQ.png" /></figure><p>❌ <strong><em>Gesture Conflicts</em></strong></p><pre>GestureDetector(<br>  onHorizontalDragUpdate: (_) {},<br>  child: PageView(...),<br>);</pre><p>This can:</p><ul><li>Block swipe-back</li><li>Conflict with system gestures</li></ul><p>✅<strong><em> Gesture-Safe Approach</em></strong></p><ul><li>Avoid horizontal gestures near screen edges</li><li>Use CupertinoPageRoute</li><li>Let iOS own navigation gestures</li></ul><h4>** Rule **</h4><blockquote>If Apple already defined a gesture, do not redefine it.</blockquote><h4>7. Motion: Match iOS Physics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4NFpAwVqwFv2uRdX78QeA.png" /></figure><p>❌<strong><em> Generic Animations</em></strong></p><pre>AnimatedContainer(<br>  duration: Duration(milliseconds: 300),<br>);</pre><p>Feels robotic.</p><p>✅<strong><em> iOS-Style Curves</em></strong></p><pre>AnimatedContainer(<br>  duration: const Duration(milliseconds: 250),<br>  curve: Curves.easeOutCubic,<br>);</pre><p>✅ <strong><em>for page transitions:</em></strong></p><pre>CupertinoPageRoute(<br>  builder: (_) =&gt; Screen(),<br>);</pre><h4>** Rule **</h4><blockquote><strong>iOS animations are: </strong>Short | Subtle | Predictable</blockquote><h4>8. Performance: 120Hz Is the Baseline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1O9Swd0nlNRY7A955XrSSg.png" /></figure><p>High-fidelity apps feel <em>effortless</em>.</p><h4>Key Flutter Rules for iOS:</h4><ul><li>Avoid rebuild storms</li><li>Keep widgets shallow</li><li>Use const aggressively</li><li>Never block UI thread</li><li>Profile on real devices</li></ul><pre>const Text(&#39;Static Content&#39;);</pre><h4>** Rule **</h4><blockquote>If scroll janks, fidelity is already lost.</blockquote><h4>9. Dark Mode: Use System Colors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oc5c0_Prq6MOvkPaqRnRrA.png" /></figure><p>❌ <strong><em>Hardcoded Colors</em></strong></p><pre>Color(0xFF000000);</pre><p>✅ <strong><em>System-Aware Colors</em></strong></p><pre>CupertinoColors.label.resolveFrom(context);</pre><p>or</p><pre>CupertinoDynamicColor.withBrightness(<br>  color: Colors.black,<br>  darkColor: Colors.white,<br>);</pre><h4>10. Flutter vs SwiftUI: The Honest Truth</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-A7aKv52MrYiTtDLIRGGQg.png" /></figure><p>Flutter <strong>can</strong> achieve high iOS fidelity — <strong>if you let iOS lead</strong>.</p><p><strong><em>Flutter fails when:</em></strong></p><ul><li>You force uniform UI</li><li>You ignore platform norms</li><li>You optimize for reuse over UX</li></ul><p><strong><em>SwiftUI wins when:</em></strong></p><ul><li>Deep system integration is needed</li><li>Apple Watch is primary</li><li>Siri / Shortcuts are core</li></ul><h4>** Rule **</h4><blockquote>High-fidelity engineering means choosing correctly — not defensively.</blockquote><h4>Final Checklist: High iOS Fidelity in Flutter</h4><p>Before shipping, ask:</p><ul><li>Does swipe-back always work?</li><li>Does text scale naturally?</li><li>Does motion feel inevitable?</li><li>Does scrolling feel physical?</li><li>Does the app disappear behind content?</li></ul><p>If yes — you’ve built a <em>real</em> iOS app with Flutter.</p><p>Here is the link to <a href="https://github.com/ShreeBhagwat/flutter_ios_fidelity">github repo</a></p><h3>Closing Thought</h3><p>Fixing a Flutter app that doesn’t feel native on iOS is rarely about rewriting everything. Most of the time, the app already works. The problem is that it was built with <strong>platform neutrality</strong> in mind on a platform that deeply values <strong>platform identity</strong>.</p><p>High iOS fidelity isn’t achieved by sprinkling Cupertino widgets or copying Apple’s UI. It comes from understanding how iOS users think, how their muscle memory works, and how the system expects apps to behave. When those expectations are met, the interface disappears — and that’s when an app truly starts to feel native.</p><p>Flutter is more than capable of delivering this level of fidelity. But it requires intention. It requires letting iOS lead in navigation, motion, typography, spacing, and gesture behavior — while using Flutter as the implementation tool, not the design authority.</p><p>If you come from a native iOS background, this mindset will feel familiar. If you don’t, the good news is that you don’t need to abandon Flutter to get there. You just need to stop treating all platforms the same.</p><p>The difference between an app that <em>runs</em> on iOS and an app that <em>belongs</em> on iOS is subtle — but users feel it immediately. And once you start building with that awareness, you can’t unsee it.</p><p>That’s when Flutter stops feeling like a compromise — and starts feeling like a craft.</p><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*-F_HadbZhAyb1a_7.gif" /></figure><figure><a href="http://buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/1*uwDXjTQ8OO_eG3_BRa7lCQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=507c4d3b8dfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Widget and Integration Test]]></title>
            <link>https://medium.com/@shreebhagwat94/widget-and-integration-test-bd019c8777bc?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd019c8777bc</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[widget-testing]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 07:43:51 GMT</pubDate>
            <atom:updated>2023-06-15T07:44:48.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XE9Cx1T3mXSi-j8WTjf05w.png" /><figcaption>Widget and Integration Test</figcaption></figure><p>This is the Fourth article in the “Master Testing In Flutter” series. The Previous articles were about Unit Testing the Http function to get all the Todos from the API, testing the change notifiers.</p><p>If you have not read the previous blogs, I would advise you to read them before you continue with the Widget and Integration Test as this is a continuation of the previous blogs. Here is the list of articles in this series, in case you want to read it.</p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a></li><li><strong>Widget and Integration Test 📍</strong></li><li><strong>Generate Goldens</strong></li><li><strong>Code Coverage</strong></li></ul><h3>Introduction</h3><p>In this session we will learn widget testing and how to Widget Test the widgets. The Main goal of widget testing is to test the UI of the application, if its rendering as intended. The main difference between a Widget Test and an Integration Test is that in Widget Test you are testing the UI of the application and in Integration Test you are testing the UI and the functionality of the application.</p><p>As I mentioned earlier Widget Tests runs in the Console, headlessly and Integration Tests runs on the device. So Widget Tests are faster than Integration Tests.</p><p>Let us start with Widget Testing. We will be writing a Widget Test for the Login Screen.</p><h4>First Widget Test</h4><p>Head over to the test folder and create a new file called as <strong>login_widget_test.dart</strong> . You will be writing your widget test code inside this file.</p><p>We always start with main function. So let us write a main function.</p><pre>// inside login_widget_test.dart file<br>void main() {<br><br>}</pre><p>In Unit Test we used to call <strong>test</strong> function to write the test. Similarly in Widget Test we will be calling a function named <strong>testWidgets</strong>. This function takes a string and a function as an argument. The string is the name of the test and the function is the test function. To call this function you need to <em>import the flutter_test package.</em></p><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br><br>void main() {<br><br>  testWidgets(&#39;Login Widget Test&#39;, (WidgetTester tester) async {<br><br>  });<br>}</pre><p><strong>WidgetTester</strong> is a class which provides a way to test widgets. You can use this class to find widgets in the widget tree, read and write the state of the widget, and verify that the widget has certain properties.</p><p>Let start writing our first widget test. When we start widget the first thing we should is try to expect a widgets presence which is static and wont change. Here we have a text widget which says <strong>Login Screen</strong>. Let us try to find this widget and check if it is present in the widget tree.</p><p>To find a if a widget is rendered we must first render the widget. It is done using the <strong>pumpWidget</strong> function. This function takes a widget as an argument and renders the widget.</p><p>so inside the testWidgets function lets pump the login screen.</p><pre><br>// inside testWidgets function<br>testWidgets(&#39;Login Widget Test&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(LoginScreen());<br>  expect(find.text(&#39;Login Screen&#39;), findsOneWidget);<br>});</pre><p>Like in unit test we had expect function to check if the test is passing or failing. Similarly in widget test we have expect function to check if the widget is present in the widget tree. The expect function takes two arguments. The first argument is the <strong>widget</strong> which you want to find and the second argument is the <strong>matcher</strong>. The matcher is a function which checks if the widget is present in the widget tree.</p><p>here we are finding the Widget by text. So we are using <strong>find.text </strong>function. This function takes a string as an argument and returns a widget. If the widget is present in the widget tree it will return the widget else it will return null. and we are using <strong>findsOneWidget</strong> matcher which checks if the widget is present in the widget tree. If the widget is present it will pass the test else it will fail the test.</p><p>Now let us run the test and see if it passes.</p><p>The Test fails with an error <em>_No MediaQuery widget ancestor found_</em> This is because we are trying to find a widget which is not present in the widget tree. So we need to add a <strong>MaterialApp</strong> widget as a parent to the LoginScreen widget.</p><pre> testWidgets(&#39;Login Widget Test&#39;, (WidgetTester tester) async {<br>    await tester.pumpWidget(<br>      ProviderScope(<br>        child: MaterialApp(<br>          home: LoginScreen(),<br>        ),<br>      ),<br>    );<br>    expect(find.text(&#39;Login Screen&#39;), findsOneWidget);<br>  });</pre><p>Run the test and it should pass now.</p><p>Congratulations you have successfuly written your first widget test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z_6yh2Wp-YQVzKy3" /><figcaption>Photo by <a href="https://unsplash.com/@eilisgarvey?utm_source=medium&amp;utm_medium=referral">Eilis Garvey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Finding Widget For Testing</h4><p>Now that we have know how to test a text widget. Lets find out other ways to find a widget in the Widget tree.</p><p>There are many ways to find a widget in the widget tree. The most common way is to find a widget by its type. For example if you want to find a widget of type <strong>Text</strong> you can use <strong>find.byType</strong> function. This function takes a type as an argument and returns a widget. If the widget is present in the widget tree it will return the widget else it will return null. and we are using <strong>findsOneWidget</strong> matcher which checks if the widget is present in the widget tree. If the widget is present it will pass the test else it will fail the test.</p><pre>testWidgets(&#39;Login Widget Test&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(home: LoginScreen()));<br>  expect(find.byType(Text), findsOneWidget);<br>});</pre><p><strong>The problem</strong> with this approach is that if you have multiple widgets of the same type in the widget tree, this function will return the first widget it finds. So if you want to find a specific widget you can use <strong>findsNWidgets </strong>matcher. This function takes a type and an integer as an argument. The integer is the number of widgets you want to find. If the number of widgets found is equal to the integer it will pass the test else it will fail the test.</p><p>Another way to find a widget is by using <strong>find.byKey</strong> function. This function takes a key as an argument and returns a widget. If the widget is present in the widget tree it will return the widget else it will return null. and we are using <strong>findsOneWidget</strong> matcher which checks if the widget is present in the widget tree. If the widget is present it will pass the test else it will fail the test.</p><pre>testWidgets(&#39;Login Widget Test&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(home: LoginScreen()));<br>  expect(find.byKey(ValueKey(&#39;loginScreenTextKey&#39;)), findsOneWidget);<br>});</pre><p>I personally prefer using <strong>find.byKey</strong> function because it is more reliable and it is easy to find a widget by its key.</p><p>If you head to <strong>key_contants.dart</strong> file you will find that we have created a key for each widget. So that we can find the widget by its key.</p><p>if not, you can just add the following code to key_constants.dart file.</p><pre>//key_constants.dart file to have all the keys<br><br>const loginScreenTextKey = ValueKey(&#39;loginScreenTextKey&#39;);<br>const emailTextFormKey = ValueKey(&#39;emailTextFormKey&#39;);<br>const passwordTextFormKey = ValueKey(&#39;passwordTextFormKey&#39;);<br>const loginButtonKey = ValueKey(&#39;loginButtonKey&#39;);<br>const loginCircularProgressKey = ValueKey(&#39;loginCircularProgressKey&#39;);<br>const loginButtonTextKey = ValueKey(&#39;loginButtonTextKey&#39;);<br>const quotesCircularProgressKey = ValueKey(&#39;quotesCircularProgressKey&#39;);<br><br>const kEmailErrorText = &#39;Please enter a valid email&#39;;<br>const kPasswordErrorText = &#39;Password must be at least 6 characters&#39;;</pre><p><strong><em>PS: Do not forget to add the key constants to widget that you want to test</em></strong></p><p>I have already passed the key values to the widgets in the login screen. So that we can find the widget by its key. Head to <strong>login_screen.dart</strong> file and you will find that we have passed the key values to the widgets.</p><pre><br>// Login screen <br>  Padding(<br>    padding: const EdgeInsets.all(10.0),<br>    child: Text(<br>      &#39;Login Screen&#39;,<br>      key: loginScreenTextKey,<br>      style: TextStyle(color: Colors.black, fontSize: 20),<br>      ),<br>    ),</pre><p>Now that we know how to find a widget in the widget tree. Lets find out how to pump a widget.</p><p>putting it simply, pumping a widget means building a widget. When you call <strong>pumpWidget</strong> function it builds the widget and returns a Future.</p><p><strong>pumpAndSettle </strong>function is used to pump a widget and wait for all animations to finish. This function takes a widget tester and a duration as an argument. The duration is the time to wait for the animations to finish.</p><p>Lets check if all the widgets present in the login screen are rendered properly. Lets write test to check that, I will be using find.byKey function to find the widgets.</p><pre>testWidgets(&#39;Login Widget Test&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(home: LoginScreen()));<br>  final loginText = find.byKey(loginScreenTextKey);<br>  expect(loginText, findsOneWidget);<br>});</pre><p>Run this test to check if our widget is rendered properly and also to test if <strong>find.byKey</strong> function works properly.</p><p><em>and the test passes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gPq4gNoEpWJgSgy1" /><figcaption>Photo by <a href="https://unsplash.com/@olav_ahrens?utm_source=medium&amp;utm_medium=referral">Olav Ahrens Røtne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Okay Here is a Cool Widget test challenge for you. I want you to write a test to check if the <strong>emailTextField, passwordTextField and loginButton are rendered properly</strong>.</p><p>I hope you were able to write the test, Here is the Solution</p><pre>testWidgets(&#39;Login Widget Test&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(home: LoginScreen()));<br>  final loginText = find.byKey(loginScreenTextKey);<br>  final emailTextField = find.byKey(emailTextFormKey);<br>  final passwordTextField = find.byKey(passwordTextFormKey);<br>  final loginButton = find.byKey(loginButtonKey);<br><br>  expect(loginText, findsOneWidget);<br>  expect(emailTextField, findsOneWidget);<br>  expect(passwordTextField, findsOneWidget);<br>  expect(loginButton, findsOneWidget);<br><br>});</pre><h4>Testing Other Scenarios of Login Page</h4><p>Now test lets test the login screen with different scenarios. Before start lets jot down the scenarios.</p><ul><li>When user enters invalid credentials</li><li>Users enters enters valid credentials</li><li>Testing the Circular loading indicator</li></ul><h4>When user enters invalid credentials</h4><p>Lets enter invalid email and password into the text form fields and tap the login button. Then we will check if the error text is displayed or not. If the error text is displayed it will pass the test else it will fail the test.</p><pre>await tester.enterText(emailTextField, &#39;abcd&#39;);<br>  await tester.enterText(passwordTextField, &#39;1234&#39;);<br><br>  await tester.tap(loginButton);<br><br>  await tester.pumpAndSettle();<br>  var emailErrorText = find.text(kEmailErrorText);<br>  var passwordErrorText = find.text(kPasswordErrorText);<br><br>  expect(emailErrorText, findsOneWidget);<br>  expect(passwordErrorText, findsOneWidget);</pre><p>We use <strong>tester.enterText</strong> function to enter text into the text form fields. This function takes a text form field and a string as an argument. The string is the text you want to enter into the text form field.</p><p>Then we tap the login button using <strong>tester.tap </strong>function. This function takes a widget as an argument. The widget is the widget you want to tap.</p><p>Then we use <strong>tester.pumpAndSettle</strong> function to wait for the animation to finish. This function takes a duration as an argument. The duration is the time you want to wait for the animation to finish.</p><p>Then we use <strong>find.text </strong>function to find the error text. This function takes a string as an argument. The string is the text you want to find.</p><p>Then we use <strong>findsOneWidget</strong> matcher to check if the error text is present in the widget tree. If the error text is present it will pass the test else it will fail the test.</p><h4>Users enters enters valid credentials</h4><p>Now that you know how to test the login screen with invalid crendetials. . lets Test the login screen for valid credentials.</p><pre>  await tester.enterText(emailTextField, &#39;abcd@mail.com&#39;);<br>  await tester.enterText(passwordTextField, &#39;abcd1234&#39;);<br><br>  await tester.tap(loginButton);<br>  await tester.pumpAndSettle();<br>  emailErrorText = find.text(kEmailErrorText);<br>  passwordErrorText = find.text(kPasswordErrorText);<br><br>  expect(emailErrorText, findsNothing);<br>  expect(passwordErrorText, findsNothing);</pre><p>Now you know how to test the Widget tests works.</p><p>There is more Widget which is missing from the test. Can you guess what it is?</p><p>The Loading Indicator, yes thats missing from the test. Lets add the loading indicator to the test.</p><p><strong>The loading indicator</strong> is shown when the user taps the login button. So we will tap the login button and check if the loading indicator is present in the widget tree. If the loading indicator is present it will pass the test else it will fail the test.</p><pre>  await tester.enterText(emailTextField, &#39;abcd@mail.com&#39;);<br>  await tester.enterText(passwordTextField, &#39;abcd1234&#39;);<br><br>  await tester.tap(loginButton);<br>  await tester.pumpAndSettle();<br>  expect(find.byKey(loginCircularProgressKey), findsOneWidget);</pre><p>Does the test pass or fails. It <strong>fails</strong>, why? Because as mentioned previously <strong>pumpAndSettle</strong> function waits for the animation to finish. But the loading indicator is shown when the user taps the login button. And pump and settles keeps on working till loading indicator is present. When the expect function checks for the loading indicator it is not present in the widget tree. So the test fails.</p><p>To fix this we will use <strong>pump</strong> function. This function takes a duration as an argument. The duration is the time you want to wait for the animation to finish.</p><pre>  await tester.enterText(emailTextField, &#39;abcd@mail.com&#39;);<br>  await tester.enterText(passwordTextField, &#39;abcd1234&#39;);<br><br>  await tester.tap(loginButton);<br>  await tester.pump(const Duration(seconds: 1));<br>  expect(find.byKey(loginCircularProgressKey), findsOneWidget);<br><br>  await tester.pump(Duration(seconds: 1));<br>  expect(find.byKey(loginCircularProgressKey), findsNothing);</pre><p>he above test will passes. We also check if loading indicator is not present in the widget tree after the animation is finished.</p><h4>Navigating to Todo Pages</h4><p>The App navigates automatically to the Todo page after the user logs in. So we will test if the App navigates to the Todo page after the users taps login button with correct credentials.</p><p>We will check for the All Todo page title to check if the App navigates to the Todo page. If the Todo page title is present in the widget tree it will pass the test else it will fail the test.</p><p>at the end of login test just write this code</p><pre> await tester.pumpAndSettle();<br>    var quotesPageTitle = find.text(&#39;Todo&#39;);<br>    expect(quotesPageTitle, findsOneWidget);</pre><p>The test fails and the Fail message is not much clear. Lets debug the test and see why its failing.</p><p>Click on the <strong>debug</strong> button instead of run button. The test will run in debug mode and its gets easier to debug the test.</p><p>The error message that we see right now is <strong>Failed to load Todos</strong> And that is cause we are not mocking the Todo data. And todo page is making a real HTTP request to fetch the quotes. So we need to mock the Todos data.</p><p>We will be using <strong>overrides</strong> to mock the Todos data. The Overrides are used to override the dependencies in the widget tree. We will override the <strong>TodoService</strong> dependency with a mock object of <strong>TodoService</strong> class.</p><p>But first lets create Mock class like we did in Unit tests and add this code to the test file on the top. To create a Mock class of our <strong>TodoService</strong> class.</p><pre>class MockTodoService extends Mock implements TodoService {}</pre><p>Inside the test function create a mock object of the TodoService class.and pass this mock object to the overrides.</p><pre>  MockTodoService mockTodoService = MockTodoService();<br>    await tester.pumpWidget(<br>      ProviderScope(<br>        overrides: [<br>          quotesNotifierProvider<br>              .overrideWith((ref) =&gt; TodoService(mockTodoService)),<br>        ],<br>        child: MaterialApp(<br>          home: LoginScreen(),<br>        ),<br>      ),<br>    );<br><br>    when(() =&gt; mockTodoService.getTodos())<br>      .thenAnswer((_) async =&gt; mockTodoService);<br>  await tester.pumpAndSettle();</pre><p>run the test and it must pass now. Also we should be able to navigate to the Todo’s page. Thats it. We are done with testing the Login Screen.</p><h4>Testing Todo Pages</h4><p>Now let us start with testing the Todos. Head over test folder and create a new file named <strong>todos_page_test.dart</strong>. To test todo page first we will have to Mock the Todos so that we can populate the Todos list in the Todos page.</p><pre>MockTodoService mockTodoService = MockTodoService();<br>   Widget createWidgetUnderTest() { <br>    await tester.pumpWidget(<br>      ProviderScope(<br>        overrides: [<br>          quotesNotifierProvider<br>              .overrideWith((ref) =&gt; TodoService(mockTodoService)),<br>        ],<br>        child: MaterialApp(<br>          home: LoginScreen(),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Here we create a Function named <strong>createWidgetUnderTest</strong> which returns a widget. This function will be used to create the widget tree for the test. We will be calling this function inside the <strong>pumpWidget</strong> method.</p><pre> testWidgets(&#39;All Todos Widget Test&#39;, (WidgetTester tester) async {<br>    await tester.pumpWidget(createWidgetUnderTest());</pre><p>We need to return mock Todos when <strong>getTodos() </strong>function is called. lets create function which will return mock Todos instead. We will adding a delay of two seconds to to depict the real world scenario. Add this function before <strong>createWidgetUnderTest</strong> function.</p><pre>  void getTodosAdter2secondsDelay() {<br>    when(() =&gt; mockTodoService.getTodos()).thenAnswer((_) async {<br>      return await Future.delayed(<br>          const Duration(seconds: 2), () =&gt; mockTodoServiceForTesting);<br>    });<br>  }<br><br></pre><pre>void getTodosAdter2secondsDelay() {<br>    when(() =&gt; mockTodoService.getTodos()).thenAnswer((_) async {<br>      return await Future.delayed(<br>          const Duration(seconds: 2), () =&gt; mockTodoServiceForTesting);<br>    });<br>  }<br><br>Widget createWidgetUnderTest() { <br>    await tester.pumpWidget(<br>      ProviderScope(<br>        overrides: [<br>          quotesNotifierProvider<br>              .overrideWith((ref) =&gt; TodoService(mockTodoService)),<br>        ],<br>        child: MaterialApp(<br>          home: LoginScreen(),<br>        ),<br>      ),<br>    );<br>  }<br><br>  getTodosAdter2secondsDelay();<br><br>  // Pump All Quotes screen<br>  await tester.pumpWidget(createWidgetUnderTest());</pre><p>First we will start by cheking if we are on the correct screen. We will check for the Todos page title to check if the App navigates to the Todos page. If the Todos page title is present in the widget tree it will pass the test else it will fail the test.</p><pre>expect(find.text(&#39;Todos&#39;), findsOneWidget);</pre><p>A simple find by text <strong>Todos </strong>can be used to check if we are on the correct screen.</p><p>Now lets test if the Todos are loading. We will check if the loading indicator is present in the widget tree. If the loading indicator is present in the widget tree it will pass the test else it will fail the test.</p><pre>  await tester.pump(const Duration(seconds: 1));<br>  expect(find.byKey(todosCircularProgressKey), findsOneWidget);<br>  await tester.pumpAndSettle();<br>  expect(find.byKey(todosCircularProgressKey), findsNothing);</pre><p>Here we also check if the loader indicator is removed from the widget tree after the todos are loaded.</p><p>Now lets test if the todos are loaded. We will check if the todos are present in the widget tree. If the todos are present in the widget tree it will pass the test else it will fail the test.</p><pre>  expect(find.text(&#39;Test Todo 1&#39;), findsOneWidget);<br>  expect(find.text(&#39;Test Todo 2&#39;), findsOneWidget);<br>  expect(find.text(&#39;Test Todo 3&#39;), findsOneWidget);<br></pre><p>Here are done widget testing of the application. Lets see how we can reuse the code that we have written for Widget Testing as Integration testing.</p><h3>Reusing Widget Test as Integration Test</h3><p>The difference between widget test and interatoin test is that, widget test runs on Console and integration test runs on the device. Now we will learn about integration test and will be resuing the widget tests into integration test.</p><p>To reuse the widget test as integration test, we first let convert the widget test into a function. Then we call this function inside the integration test. Let us see how to do this.</p><p>Head over to login_widget_test.dart and create a function called as <strong>loginWidgetTest</strong> and move the test code inside this function.it will look like this.</p><pre>Future&lt;void&gt; loginWidgetTest(<br>    WidgetTester tester) async {<br>      <br> MockTodoService mockTodoService = MockTodoService();<br>    await tester.pumpWidget(<br>      ProviderScope(<br>        overrides: [<br>          quotesNotifierProvider<br>              .overrideWith((ref) =&gt; TodoService(mockTodoService)),<br>        ],<br>        child: MaterialApp(<br>          home: LoginScreen(),<br>        ),<br>      ),<br>    );<br><br>    when(() =&gt; mockTodoService.getTodos())<br>      .thenAnswer((_) async =&gt; mockTodoService);<br>  await tester.pumpAndSettle();<br><br><br>  final loginText = find.byKey(loginScreenTextKey);<br>  final emailTextField = find.byKey(emailTextFormKey);<br>  final passwordTextField = find.byKey(passwordTextFormKey);<br>  final loginButton = find.byKey(loginButtonKey);<br><br>  expect(loginText, findsOneWidget);<br>  expect(emailTextField, findsOneWidget);<br>  expect(passwordTextField, findsOneWidget);<br>  expect(loginButton, findsOneWidget);<br><br><br><br>  await tester.enterText(emailTextField, &#39;abcd&#39;);<br>  await tester.enterText(passwordTextField, &#39;1234&#39;);<br><br>  await tester.tap(loginButton);<br><br>  await tester.pumpAndSettle();<br>  final emailErrorText = find.text(kEmailErrorText);<br>  final passwordErrorText = find.text(kPasswordErrorText);<br><br>  expect(emailErrorText, findsOneWidget);<br>  expect(passwordErrorText, findsOneWidget);<br><br><br><br>  await tester.enterText(emailTextField, &#39;abcd@mail.com&#39;);<br>  await tester.enterText(passwordTextField, &#39;abcd1234&#39;);<br><br>  await tester.tap(loginButton);<br><br>  await tester.pump(const Duration(seconds: 1));<br>  expect(find.byKey(loginCircularProgressKey), findsOneWidget);<br><br><br>  await tester.pump(Duration(seconds: 1));<br>  expect(find.byKey(loginCircularProgressKey), findsNothing);<br> <br>  expect(emailErrorText, findsNothing);<br>  expect(passwordErrorText, findsNothing);<br><br>  await tester.pumpAndSettle();<br><br>  var todosPageTitle = find.byKey(todosTextKey);<br>  expect(todosPageTitle, findsOneWidget);<br><br>}</pre><p>We will call this function inside the main function.</p><pre>void main(){<br>    testWidgets(&#39;Login Widget Test&#39;, loginWidgetTest);<br>}</pre><p>Run the login widget test just to check if our refactor has not broken anything.</p><p>Just like we refactored the login widget test, we have to do the same for the todos widget test.</p><pre>void main() {<br>  testWidgets(&#39;All Quotes Widget Test&#39;, allQuotesWidgetTest);<br>}<br><br>Future&lt;void&gt; allTodosWidgetTest(WidgetTester tester) async {<br>  MockTodoService mockTodoService = MockTodoService();<br><br>void getTodosAdter2secondsDelay() {<br>    when(() =&gt; mockTodoService.getTodos()).thenAnswer((_) async {<br>      return await Future.delayed(<br>          const Duration(seconds: 2), () =&gt; mockTodoServiceForTesting);<br>    });<br>  }<br><br>Widget createWidgetUnderTest() { <br>    await tester.pumpWidget(<br>      ProviderScope(<br>        overrides: [<br>          quotesNotifierProvider<br>              .overrideWith((ref) =&gt; TodoService(mockTodoService)),<br>        ],<br>        child: MaterialApp(<br>          home: LoginScreen(),<br>        ),<br>      ),<br>    );<br>  }<br><br>  getTodosAdter2secondsDelay();<br><br>  // Pump All Todos screen<br>  await tester.pumpWidget(createWidgetUnderTest());<br><br>  expect(find.text(&#39;Todos&#39;), findsOneWidget);<br><br>  await tester.pump(const Duration(seconds: 1));<br>  expect(find.byKey(todosCircularProgressKey), findsOneWidget);<br>  await tester.pumpAndSettle();<br>  expect(find.byKey(todosCircularProgressKey), findsNothing);<br><br>  expect(find.text(&#39;Test Todo 1&#39;), findsOneWidget);<br>  expect(find.text(&#39;Test Todo 2&#39;), findsOneWidget);<br>  expect(find.text(&#39;Test Todo 3&#39;), findsOneWidget);<br>}</pre><p>Now that we have refactored the widget tests, we can reuse them in the integration test.</p><p>Create a new folder called as <strong>integration_test</strong> inside the root folder. Inside this folder create a new file called as <strong>**integration_test.dart**</strong>.</p><p>Event the integration test in written inside the main function so lets create a main function.</p><pre>void main(){<br>    <br>}</pre><p>We have to multiple widget tests to run in the integration test. So we will use the group function.</p><pre>void main(){<br>    group(&#39;Integratoin&#39;, () {<br>        <br>    });<br>}</pre><p>the <strong>group</strong> function runs multiple tests in a group. The first parameter is the name of the group and the second parameter is a function which contains the tests. In this group we will run the login widget test and the quotes widget test.</p><pre>   testWidgets(&#39;Login-Page&#39;, (tester) =&gt; loginWidgetTest(tester));<br>   testWidgets(&#39;All-Todo-Page&#39;, (tester) =&gt; allTodosWidgetTest(tester));</pre><p>before running the integration test, we have to make sure that our Flutter widgets are ready. So we have to call the <strong>WidgetsFlutterBinding.ensureInitialized()</strong> function before running the integration test. Finally it will look like this.</p><pre>void main() {<br>  IntegrationTestWidgetsFlutterBinding.ensureInitialized();<br>  group(&#39;Integration Tests&#39;, () {<br> testWidgets(&#39;Login-Page&#39;, (tester) =&gt; loginWidgetTest(tester));<br>   testWidgets(&#39;All-Todo-Page&#39;, (tester) =&gt; allTodosWidgetTest(tester));<br>  });<br>}</pre><p>Now to run integration test, we need a device to run. So open emulator, simulator or just connect your device to the computer and run the following command.</p><pre>flutter test integration_test/integration_tests.dart</pre><p>The integration test will run on the device and you can see the the app running on the device.</p><p>This is how we can reuse the widget tests as integration tests which saves a lot of time and effort</p><p>Here I conclude the Fourth article from<strong> Master Testing in Flutter </strong>series. In this article, I explained how you can Test the <strong>Widgets rendered on UI </strong>mock data with the <strong>Mocktail </strong>package. Reuse Widget Test as <strong>Integration</strong> <strong>test</strong> to save time.</p><p>This also concludes the <strong>Widget and Integration Testing</strong> part of our Testing Series. In the next article. I will cover <strong>Generate Goldens</strong>, and concepts of testing a widget.</p><p>If you want to check out the rest of the blogs from the testing Series here is a list of all the blogs present. I would still address if you follow this guide step by step.</p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a><strong>📍</strong></li><li><strong>Widget and Integration Test 📍</strong></li><li><strong>Generate Goldens</strong></li><li><strong>Code Coverage</strong></li></ul><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below. I would like to know what are the other way to globally listen to network connectivity.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*bkNbz0dhGP8H5wd0.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*B_ffFOiRDqdJZ_W4.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd019c8777bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Test the Change Notifier in Flutter]]></title>
            <link>https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/74fb75e8fe58</guid>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 14:20:55 GMT</pubDate>
            <atom:updated>2023-04-02T14:21:20.840Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Shree Bhagwat — Codeaamy</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PPry7GIMexHdRAGoi3Q_A.png" /></figure><p>This is the Third article in the “Master Testing In Flutter” series. The Previous article was about Unit Testing the Http function to get all the quotes from the API. If you have not read the previous blogs, I would advise you to read them before you continue with the Unit Test the Change Notifier. Here is the list of other articles in this series, in case you want to read it.</p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a><strong>📍</strong></li><li><strong>Widget and Integration Test</strong></li><li><strong>Generate Goldens</strong></li><li><strong>Code Coverage</strong></li></ul><p>Let&#39;s start with <strong>Unit Testing the Change Notifier</strong>. As we previously discussed in Unite Test we test small functions or classes. Before starting with testing let us first explore the todo_notifier . Navigate to todo_notifier.dart</p><pre>class TodoNotifier extends ChangeNotifier {<br>  final TodoService _todoService;<br><br>  TodoNotifier(this._todoService);<br><br>  List&lt;Todo&gt; _todos = [];<br>  List&lt;Todo&gt; get todos =&gt; _todos;<br><br>  bool _isLoading = false;<br>  bool get isLoading =&gt; _isLoading;<br><br>  void setLoader(bool value) {<br>    _isLoading = value;<br>    notifyListeners();<br>  }<br><br>  Future getTodos() async {<br>    setLoader(true);<br>    _todos = await _todoService.getTodos();<br>    setLoader(false);<br>  }<br>}<br><br>final _client = Client();<br>final todosNotifierProvider =<br>    ChangeNotifierProvider((ref) =&gt; TodoNotifier(TodoService(_client)));</pre><ul><li>This code defines a TodoNotifier class that extends ChangeNotifier, a class provided by the Flutter framework that can notify its listeners when its state changes.</li><li>The TodoNotifier class has a _todoService property that represents an instance of a TodoService class, which communicates with a backend API to fetch todo items.</li><li>The _todos property is a list of Todo objects, and the getTodos method fetches the todos from the API by calling _todoService.getTodos(). The setLoader method is used to toggle the _isLoading boolean property, which represents whether the todos are currently being fetched or not.</li><li>When the setLoader method is called, it sets the _isLoading property to the passed value and notifies its listeners of the state change by calling notifyListeners().</li><li>The isLoading property returns the current value of _isLoading. The todos property returns the current value of _todos.</li><li>Finally, the code defines a todosNotifierProvider variable that creates a ChangeNotifierProvider instance. The ChangeNotifierProvider is a widget that provides the TodoNotifier instance to its child widgets via the Provider package. The TodoNotifier instance is constructed with an instance of TodoService, which is constructed with a Client instance.</li></ul><h4>Test Change Notifier</h4><p>Create a new file todo_change_notifier_test.dart in a test folder. This is where we will write the tests to test the change notifier. Add the following test code in the main function.</p><pre>void main() {<br>  late TodoNotifier sut_todoNotifier;<br><br>  setUp(() {<br>    sut_todoNotifier = TodoNotifier();<br>  });<br>}</pre><p>The above code declares a variable named sut_todoNotifier of type TodoNotifier as late, which means that it is uninitialized but will be assigned a value before it is used.</p><p>The prefix sut is commonly used as a naming convention in software testing to indicate that this is a <strong>System Under Test (SUT)</strong> object, which is the object being tested.</p><p>The setUp() function is used to set up the<strong> test environment </strong>before running each test case. In this case, it initializes the sut_todoNotifier variable by creating a new instance of the TodoNotifier class.</p><p>sut_todoNotifier = TodoNotifier() throws an error as it requires TodoService at the time of initialisation.</p><p>We have to use a mock object like MockTodoService which is useful in testing scenarios where the real TodoService object is difficult to use, has unpredictable behaviour, or is unavailable. By using a mock object, developers can isolate the behaviour of the TodoService and test the behaviour of other parts of the system without worrying about the state of the TodoService itself.</p><h4>Mocking Data with Mocktail</h4><p>Add the following code on top of</p><pre>class MockTodoService extends Mock implements TodoService {}</pre><blockquote>Note: — You will need to add mocktail package in the pubspec.yaml</blockquote><p>This code defines a mock class called MockTodoService that extends the Mock class and implements the TodoService interface. The Mock class is part of a testing <strong>mocktail</strong> that allows developers to create mock objects that simulate the behaviour of real objects for testing purposes.</p><p>By extending Mock, the MockTodoService class inherits methods that can be used to set up expectations and define behaviour for the mock object. These expectations and behaviours can be used to test how other parts of the system interact with the TodoService object.</p><p>Pass the MockTodoService variable inside the constructor of sut_todoNotifier();</p><pre>  late TodoNotifier sut_todoNotifier;<br>  late MockTodoService mockTodoService;<br><br>  setUp(() {<br>    mockTodoService = MockTodoService();<br>    sut_todoNotifier = TodoNotifier(mockTodoService);<br>  });</pre><h4>Initial Testing</h4><p>First, we have to test the Initial values when the change notifier initialises</p><pre>  test(&#39;Should check initial values are correct&#39;, () {<br>    expect(sut_todoNotifier.isLoading, false);<br>    expect(sut_todoNotifier.todos, []);<br>  });</pre><p>The first assertion checks that the isLoading property is initially set to false. This means that when the TodoNotifier object is created, it should not be in a loading state.</p><p>The second assertion checks that the todos property is initially set to an empty list. This means that when the TodoNotifier object is created, it should not contain any <strong>todos</strong>.</p><pre>  void getTodoServiceReturnsQuotes() {<br>    when(() =&gt; mockTodoService.getTodos())<br>        .thenAnswer((_) async =&gt; mockTodosForTesting);<br>  }</pre><p>This code is defining a mock behaviour for a TodoService instance using the mockTodoService object. Specifically, it is defining the behaviour of the getTodos() method of the TodoService.</p><p>The when() function is a part of the <strong>mocktail</strong> library, and it is used to define the behaviour of a mocked object when a specific method is called on it. In this case, when() is called with an anonymous function that returns the result of calling getTodos() on the mockTodoService object.</p><p>The thenAnswer() method is called on the result of the when() function, and it defines the behaviour that should be returned when the method is called. In this case, it is returning a Future that resolves to mockTodosForTesting, which is a predefined list of Todo objects that are being used for testing purposes. It is located in key_constants.dart file</p><p>Overall, this code is defining a <strong>mock</strong> behaviour for a TodoService instance that always returns a predefined list of Todo objects when its getTodos() method is called. This is useful for testing code that relies on the behaviour of the TodoService without actually having to interact with a real instance of the service.</p><h4>Testing the getTodo function</h4><p>Now let&#39;s test the <strong>getTodo</strong> function from our <strong>Change Notifier. </strong>Add the following test code.</p><pre>  test(&#39;&#39;&#39;Loading data indicator, <br>      sets Todos, indicates data is not loaded anymore&#39;&#39;&#39;, () async {<br>    getTodoServiceReturnsQuotes();<br>    final future = sut_todoNotifier.getTodos();<br>    expect(sut_todoNotifier.isLoading, true);<br>    await future;<br>    expect(sut_todoNotifier.todos, mockTodosForTesting);<br>    expect(sut_todoNotifier.isLoading, false);<br>  });</pre><p>The test uses the getTodoServiceReturnsQuotes() function to simulate the loading of Todos, which likely retrieves the Todos from a service or data source. Then, the test calls the getTodos() method and verifies that the loading state of the sut_todoNotifier instance is set to true.</p><p>After that, the test awaits the completion of the future variable, which should represent the loading of the Todos. Once the loading is complete, the test verifies that the Todos have been correctly loaded by checking that the todos property of sut_todoNotifier contains the expected values.</p><p>Finally, the test checks that the loading state of the sut_todoNotifier instance is set to false after the Todos have been loaded.</p><p><strong>Grouping All The Tests</strong></p><p>Now we have successfully written all the tests for our change notifier, you can run each test and check. Also, you will notice that we have to run each test separately which is a tedious task.</p><p>Let’s group all the tests so that we can run them all together.</p><pre>group(&#39;Group of Tests for testing change notifier&#39;, () {});</pre><p>Just as we have test function to write the tests, we have a group function, which groups all the tests written. Just add the written tests inside the callback function of the group test.</p><p>Finally todo_change_notifier_test.dart should look like this.</p><pre><br>class MockTodoService extends Mock implements TodoService {}<br><br>void main() {<br>  late TodoNotifier sut_todoNotifier;<br>  late MockTodoService mockTodoService;<br><br>  setUp(() {<br>    mockTodoService = MockTodoService();<br>    sut_todoNotifier = TodoNotifier(mockTodoService);<br>  });<br><br>  group(&#39;Group of Tests for testing change notifier&#39;, () {<br>    test(&#39;Should check initial values are correct&#39;, () {<br>      expect(sut_todoNotifier.isLoading, false);<br>      expect(sut_todoNotifier.todos, []);<br>    });<br><br>    void getTodoServiceReturnsQuotes() {<br>      when(() =&gt; mockTodoService.getTodos())<br>          .thenAnswer((_) async =&gt; mockTodosForTesting);<br>    }<br><br>    test(&#39;&#39;&#39;Loading data indicator, <br>      sets Todos, indicates data is not loaded anymore&#39;&#39;&#39;, () async {<br>      getTodoServiceReturnsQuotes();<br>      final future = sut_todoNotifier.getTodos();<br>      expect(sut_todoNotifier.isLoading, true);<br>      await future;<br>      expect(sut_todoNotifier.todos, mockTodosForTesting);<br>      expect(sut_todoNotifier.isLoading, false);<br>    });<br>  });<br>}</pre><p>Here I conclude the third article from<strong> Master Testing in Flutter </strong>series. In this article, I explained how you can Test the <strong>Change Notifier and </strong>mock data with the <strong>Mocktail </strong>package.</p><p>This also concludes the <strong>Unit Testing</strong> part of our Testing Series. In the next article. I will cover <strong>Widget Testing</strong>, and concepts of testing a widget.</p><p>If you want to check out the rest of the blogs from the testing Series here is a list of all the blogs present. I would still address if you follow this guide step by step.</p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a><strong>📍</strong></li><li><strong>Widget and Integration Test</strong></li><li><strong>Generate Goldens</strong></li><li><strong>Code Coverage</strong></li></ul><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below. I would like to know what are the other way to globally listen to network connectivity.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*45I1c5oMJuASZYk5.gif" /></figure><figure><a href="https://www.buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/0*JCaW6fheVPi58uGk.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74fb75e8fe58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Test In Flutter]]></title>
            <link>https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/db260cf64829</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 14:17:35 GMT</pubDate>
            <atom:updated>2023-04-02T14:22:43.772Z</atom:updated>
            <content:encoded><![CDATA[<p><em>by Shree Bhagwat — Codeaamy</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kpXg9xaPNDiAWDd0_4RTA.png" /></figure><p>This is the second article in the “Master Testing in Flutter” series. The first article was an introduction to Testing and different types of tests in Flutter. If you have not read that, I would advise you to read that article <strong>here</strong> before you continue with the <strong>Unit Test. </strong>Here is the list of other articles in this series, in case you want to read it.</p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a><strong>📍</strong></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a></li><li><strong>Widget and Integration Test (CS)</strong></li><li><strong>Generate Goldens (CS)</strong></li><li><strong>Code Coverage (CS)</strong></li></ul><p>let&#39;s start with <strong>Unit Testing</strong> in Flutter. In unit tests, we test a small function, method or class. This helps us to check if the function is running as expected or if there are any issues in that block of code that we have just written.</p><p>In this article, we are going over the following topics.</p><ul><li><strong>Understanding the project.</strong></li><li><strong>Writing first unit test</strong></li><li><strong>Testing HTTP function</strong></li><li><strong>Mocking data for HTTP function.</strong></li><li><strong>Testing ChangeNotifier.</strong></li><li><strong>Using mocktail for Mocking data.</strong></li></ul><h3>What Are We Going To Test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*YrCz4TSRv_pRgw0zsJefmA.gif" /><figcaption>Working of a Todo Application</figcaption></figure><p>Above you can see a Todo Application which has a login screen which takes an email and password. to authenticate the user and navigate the user Todos screen where we display a list of all the todos. The login form has a validator which checks for email and password length. The Todos on the screen are fetched from an <strong>HTTP get request</strong>.</p><p>I wanted to keep the main app simple so that we can have more focus on the testing.</p><h4>Understanding the Project</h4><p>You can download the Starter Project from here -&gt; <a href="https://github.com/ShreeBhagwat/testing_in_flutter_blog">Testing In Flutter</a>. <em>(Follow me on GitHub 🥹). </em>Open the starter project in you your favourite. I am using VS Code, but you can use Android Studio or any other IDE which you are comfortable with. This is what you will have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndtdlEfwVqxFELQzqmaAGw.png" /><figcaption>Todo App Starter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*z9BuqfW-MSrQIPl0jROxSQ.png" /><figcaption>Structure of the Project.</figcaption></figure><p>The model folds consist of the Todo Model which helps us to display the Todo on the Screen.</p><p>The Notifier folder has two notifier classes — LoginNotifier and TodoNotifier which extends ChangeNotifier. These notifiers will be used to manage the State of the App and also provide the required dependencies.</p><p>Pages folder consists of the UI Pages — LoginPage and AllTodoPage. The services folder has the TodoService which is responsible for fetching the Todos from the http request.</p><p>key_constants.dart contains some constants and mock data. Lets ignore that for now.</p><p>We have already added some packages that we are going to need for the testing and our application. Here flutter_test and integration_test is responsible for running tests and mocktail is used to mock the data.</p><pre>  cupertino_icons: ^1.0.2<br>  flutter_riverpod: ^2.2.0<br>  http: ^0.13.5<br><br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  integration_test:<br>    sdk: flutter    <br>  flutter_lints: ^2.0.0<br>  mocktail: ^0.3.0</pre><p>We will be using our test folder to write all the tests.</p><h4>Writing Your First Unit Test</h4><p>Ok, we have explored a lot in theory and now its time to write your First Unit Test.</p><p>Create a new file named todo_json_test.dart inside the test folder.</p><p>as you know in flutter we need main method to run our app, just like that, we need main method to run our tests also.</p><h4>Understanding components of flutter_test</h4><p>To test the Flutter application we need functions which will help us to run the test code. We get those functions from flutter’s official package flutter_test . It has already been implemented in pubspec.yaml .</p><p>lets see some of the components that we we will need for<strong> Unit Test</strong>. The rest of the components will be explored later on.</p><ul><li>test() — a test function which helps to run tests of Flutter app. This function takes a String (name of the Test) and callback body function where we will be writing our test.</li><li>expect(actual, matcher) — expect function has two parameters; actual and matcher actual is the data that we get, and compare with the matcher value. If the actual and matcher value matches, the test <strong>passes</strong> and if these values do not match, the test <strong>fails</strong>.</li></ul><p><strong>Testing the Todo Model</strong></p><p>inside the main() function let us write the test to test the todo model</p><pre>void main() {<br>  test(&#39;Todo json test&#39;, () {<br>    final todo = Todo(1, &#39;title&#39;, false, 1);<br>    <br>    expect(todo.id, 1);<br>    expect(todo.todo, &#39;title&#39;);<br>    expect(todo.completed, false);<br>    expect(todo.userId, 1);<br>  });<br>}</pre><p>Create a todo object with dummy data, and then let&#39;s test the todo object. <br>Here we expect each value with the dummy data that we have given. This is to test the Model data we have created. If we change the Model data in future, this test will <strong>fail</strong> and we will notice the change,</p><p>Now click on the <strong>run </strong>to run the written test and you will see the test <strong>passing</strong> and <strong>green ticks</strong> on the left of the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*HnWzRqoNG3tbfNJ451oNGQ.png" /><figcaption>Running todo model test</figcaption></figure><p>Now let us change some of the values of matcher in expect function and re-run the test. The test will fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*N8Ba9p25l8BtSKJnyNz1-g.png" /><figcaption>Failed Unit test as actual and matcher values are not matching.</figcaption></figure><p>This is how we can check if the written function is as per expectation or if something different is happening. That&#39;s why a unit test is important.</p><h3>Unit Test of an HTTP Function</h3><p>An application is almost incomplete without making an HTTP request either to send some data or get some data from the backend. These are very crucial functions in an app cause chances are very high that there might be bugs in fetching and parsing the data, so testing the HTTP function is very important.</p><p>But there are times when testing we might face internet issues which can fail the test and give improper test results, hence when we test an HTTP function we have to mock the data.</p><h4>Mocking Data</h4><p>Mocking data means, passing dummy or mock data as per the required module to test a function or a widget.</p><p>We have already created the mock data that we are going to use. Navigate to key_constants.dart and scroll down to mockTodos .</p><pre>final mockTodos = jsonEncode(data);<br><br>final data = {<br>  &quot;todos&quot;: [<br>    {&quot;id&quot;: 1, &quot;todo&quot;: &quot;Create testing blog&quot;, &quot;completed&quot;: true, &quot;userId&quot;: 1}<br>  ],<br>};</pre><p>You can see data is an exact replica of the response that you get from the HTTP function. This mock data will be used to test the HTTP function.</p><p>Navigate to todo_json_test.dart and below the previous test inside the main() add the following code.</p><pre>  test(&#39;Todo Service MOCK HTTP&#39;, () async {<br>    Future&lt;Response&gt; _mockHttp(Request request) async {<br>      if (request.url.toString().startsWith(&#39;https://dummyjson.com/todo&#39;)) { //<br>        return Response(mockTodos, 200,<br>            headers: {HttpHeaders.contentTypeHeader: &#39;application/json&#39;});<br>      }<br><br>      return throw Exception(&#39;failed&#39;);<br>    }<br><br>    final apiService = TodoService(MockClient(_mockHttp));<br><br>    final quotes = await apiService.getTodos();<br><br>    expect(quotes.first.id, 1);<br>    expect(quotes.first.todo, &#39;Create testing blog&#39;);<br>    expect(quotes.first.completed, true);<br>    expect(quotes.first.userId, 1);<br>  });</pre><ul><li>Create a Future function _mockHttp(Request request) which will return the <strong>mock data</strong> as the response when you call the function.</li><li>At first, you check if the <strong>API URL</strong> starts with the same <strong>API URL </strong>that you have in the real function. If the API matches you return the response with mockTodo and the response code as 200.</li><li>Create a TodoService variable which takes MockClient as an HttpClient.</li><li>You call getTodos() and save the response in the variable named quotes.</li><li>expect() function checks the matcher value with the actual value of the response</li><li>The mock values are returned from the _mockHttp function when getTodo function is called.</li></ul><p>Run the test and it should <strong>pass</strong>. If you change the URL or the matcher value the test function will <strong>fail</strong>. This helps us to test the response and <strong>URL</strong> that is used in the HTTP function.</p><p>As mentioned above Unit Tests are used to test a function or a class. Here we have used Unit Tests to test the HTTP function which makes a GET request to fetch todos from the <strong>API</strong>.</p><p>Here I conclude the second article from the Master Testing in Flutter Series. In the next Blog, we will explore How to Unit Test the ChangeNotifier that we have used in the app to manage the state and dependencies of the Application.</p><p>If you want to check out the rest of the blogs from the testing Series here is a list of all the blogs present. I would still address if you follow this guide step by step.</p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a><strong> 📍</strong></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a></li><li><strong>Widget and Integration Test (CS)</strong></li><li><strong>Generate Goldens (CS)</strong></li><li><strong>Code Coverage (CS)</strong></li></ul><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below. I would like to know what are the other way to globally listen to network connectivity.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*45I1c5oMJuASZYk5.gif" /></figure><figure><a href="https://www.buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/0*JCaW6fheVPi58uGk.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db260cf64829" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Testing in Flutter.]]></title>
            <link>https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/62dcb25fd48d</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 13:59:52 GMT</pubDate>
            <atom:updated>2023-04-02T14:21:46.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_12m6Gn5VvM8KKEJE8-cIg.png" /><figcaption>Master Testing In Flutter — Part 1: Introduction To Flutter</figcaption></figure><p>You guys have seen this screen multiple times in your app development journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*dak_Xg-zmzJ9DXVC3Zq4Ow.png" /><figcaption>Flutter Index Value not in range error.</figcaption></figure><p>This is due to some code not working as it was supposed to. Or that you have missed handled some of the code. Altogether this is terrible behaviour which will push users to delete the application.</p><p><strong>So how can we Prevent it? </strong>The answer is simple, fix the bug right?</p><p>Well, it’s not that simple. To fix the bug it’s very important to actually find the bug. This is when <strong>testing</strong> comes into play. The more you test your app, the more bugs you can find to fix and make your app bug free.</p><p>Adding more features also adds unnecessary bugs. Hence we should test apps from time to time as we do not want the application to crash in production.</p><p>In this blog series, you will learn how you can test your flutter app, different kinds of tests in Flutter, the amount of code you test covers and generate Goldens (UI Snapshot) to test the UI changes that take place in the app.</p><p>This series will be divided into multiple sections making it easier to follow and jump to required the section as per your requirement. We will be Testing a <a href="https://github.com/ShreeBhagwat/testing_in_flutter_blog">Todo Application </a>— The application does an Http request to fetch todos and displays them on the list. I would suggest following the tutorial from the start so it will be easier to understand and follow along</p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a><strong> 📍</strong></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a></li><li><strong>Widget and Integration Test (CS)</strong></li><li><strong>Generate Goldens (CS)</strong></li><li><strong>Code Coverage (CS)</strong></li></ul><h3>Introduction to Testing and Types of Testing in Flutter</h3><p><strong>Ways of Testing an App ( Brief — just key point)</strong></p><p>There are two ways you can test your app.</p><ul><li><strong>Manual Testing </strong>— Run the app and test Manually</li><li><strong>Automated Testing </strong>— Write code which runs and tests the application.</li></ul><p><strong>Disadvantages of Manual Testing</strong></p><ul><li>Time-Consuming.</li><li>The app can work as expected but can have underneath bugs, this will be missed by manual testing.</li><li>Difficult to test big apps.</li><li>Bad for the TDD approach,</li></ul><p><strong>Advantages of Automated testing</strong></p><ul><li>Automated Tests are Fast and do not require a separate person to run them.</li><li>You cover all/most of the code.</li><li>Increasing the app won’t hamper the test process.</li><li>Easier to find bugs and fix them.</li><li>Best to have a TDD approach.</li></ul><h4>Different Types of Tests in Flutter</h4><ul><li><strong>Unit Test</strong> — Tests a single function, method or class.</li><li><strong>Widget Test</strong> — Test a single Widget or flow of Widgets. (Runs headless in Console)</li><li><strong>Integration Test</strong> — Tests the complete app or a large part of an app. (Requires a device, physical or Simulator)</li></ul><h4>CMDE Table — Confidence Maintenance Dependencies Execution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*BNG0pq8H1whb22OjMjRwCw.png" /><figcaption>CMDE Table</figcaption></figure><p><strong>CMDE</strong> table lets us know the values we get from each test. As you can see,</p><ul><li><strong>Confidence</strong> — Unit test has the lowest confidence as you are just testing a small function or a class. Whereas the Integration test has the highest confidence as you are testing an Entire widget that too with a given environment.</li><li><strong>Maintenance — </strong>It’s easy to maintain unit tests as compared to widgets and integration tests. We will see the reason later on.</li><li><strong>Dependencies</strong> — The Dependencies management in the unit test is few and is the most in the Integration.</li><li><strong>Execution</strong> — Unit Tests are executed very quickly and hence save a lot of time while running. And Integration test consumes the most time while running as it actually installs the entire application on the device and then tests it.</li></ul><p><strong>Which Tests To Run When </strong>(Non-TDD approach)</p><ul><li>Unit Test after every function.</li><li>Widget and Integration Test before creating PR.</li></ul><p>This is a general introduction to Tests and Testing in Flutter. In this article, you got an overview of different kinds of tests and their use cases. In the next blog, we will start with setting up our test project and writing our first <strong>Unit Test.</strong></p><ul><li><a href="https://medium.com/@shreebhagwat94/master-testing-in-flutter-62dcb25fd48d"><strong>Introduction to Testing and Types of Testing in Flutter</strong></a><strong> 📍</strong></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-in-flutter-db260cf64829"><strong>Unit Test</strong></a></li><li><a href="https://medium.com/@shreebhagwat94/unit-test-the-change-notifier-in-flutter-74fb75e8fe58"><strong>Unit Test the Change Notifier</strong></a></li><li><strong>Widget and Integration Test (CS)</strong></li><li><strong>Generate Goldens (CS)</strong></li><li><strong>Code Coverage (CS)</strong></li></ul><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below. I would like to know what are the other way to globally listen to network connectivity.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*45I1c5oMJuASZYk5.gif" /></figure><figure><a href="https://www.buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/0*JCaW6fheVPi58uGk.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62dcb25fd48d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle Internet Connectivity In Flutter With Riverpod]]></title>
            <link>https://medium.com/@shreebhagwat94/handle-internet-connectivity-in-flutter-with-riverpod-bbde21c187dc?source=rss-ae2241179909------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbde21c187dc</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Shrihriday Bhagwat]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 08:54:54 GMT</pubDate>
            <atom:updated>2022-12-27T08:54:54.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="handle internet connectivity in Flutter with Riverpod" src="https://cdn-images-1.medium.com/max/1024/1*tCwKPy_FrL5hSStjrVSkKg.png" /><figcaption>Handle internet connectivity in Flutter with Riverpod.</figcaption></figure><p>Getting data from Rest API making an HTTP request and displaying the data on the screen is the most basic and crucial task in an App. This process happens as the user is interacting with the application and an internet connection is required constantly to retrieve the data from the API.</p><p>If there is no internet connection chances are the app will keep showing the loading symbol and the user will think that the app is broken, or there is some bug in the app.</p><p>App developers must inform the user about Internet connectivity to help the user.</p><p>Here we will discuss how to check the internet connectivity of an app built in Flutter.</p><h3>What are we going to Build?</h3><p>For this, we will build a basic application which shows the internet connection status on the screen and a snack bar about the same. This will listen to the internet connection status so we get real-time network updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0xwhiObOL5pRrYehyzNsg.gif" /></figure><h3>Let&#39;s Get Started</h3><p>Let&#39;s start by creating a Flutter application which has a Text in the Center which says <strong>Connectivity Status</strong> and is <strong>Connected to internet Text</strong>. I have used a dark background but you can use whichever background colour you want.</p><h4>Adding Pub Packages</h4><p>For this application, we are going to use two packages.</p><ul><li><a href="https://pub.dev/packages/connectivity_plus">connectivity_plus</a>: A plugin which allows the Flutter app to discover network connectivity and configure the app accordingly.</li><li><a href="https://pub.dev/packages/flutter_riverpod">flutter_riverpod</a>: A state management library which helps to manage the state of the app and provide the dependencies.</li></ul><p>let&#39;s start by adding these two packages to our application. To do so add the packages to pubspec.yaml file</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  connectivity_plus: ^3.0.2<br>  flutter_riverpod: ^2.1.1</pre><blockquote>Note: Do not forget to run flutter pub get after adding dependencies</blockquote><h3>Connectivity Status Notifier</h3><p>let us create a Connectivity status Notifier file which will have all the code to notify the app about the network connection. We will create a class with the same name which extends to StateNotifier.</p><blockquote>A StateNotifier is a simple solution to control state in an immutable manner and is a recommended solution for managing state when using Provider and Riverpod.</blockquote><p>When extending to StateNotifier we need to provide a Type for the StateNotifier. Let&#39;s create an enum which will have the connectivity status which we will track the state of.</p><pre>enum ConnectivityStatus { NotDetermined, isConnected, isDisonnected }<br><br>class ConnectivityStatusNotifier extends StateNotifier&lt;ConnectivityStatus&gt; {}</pre><h4>Listen to ConnectivityResult changes.</h4><p>Add the following code to the ConnectivityStatusNotifier</p><pre> ConnectivityStatus? lastResult;<br>  ConnectivityStatus? newState;<br><br>  ConnectivityStatusNotifier() : super(ConnectivityStatus.isConnected) {<br>    if (state == ConnectivityStatus.isConnected) {<br>      lastResult = ConnectivityStatus.isConnected;<br>    } else {<br>      lastResult = ConnectivityStatus.isDisonnected;<br>    }<br>    lastResult = ConnectivityStatus.NotDetermined;<br>   <strong> Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {<br>      switch (result) {<br>        case ConnectivityResult.mobile:<br>        case ConnectivityResult.wifi:<br>          newState = ConnectivityStatus.isConnected;<br>          break;<br>        case ConnectivityResult.none:<br>          newState = ConnectivityStatus.isDisonnected;<br>          break;<br>      }</strong><br>      if (newState != lastResult) {<br>        state = newState!;<br>        lastResult = newState;<br>      }<br>    });<br>  }</pre><p>First, we create two nullable variables of type ConnectivityStatus named as lastState and newState. When the connectivity status changes we will update these variables.</p><p>Using the super constructor to listen to changes taking place in the connectivity status of the device. The Switch lets us check the connectivity status and then update the value to the newState variable that we have created on top.</p><h4>State Notifier Provider</h4><pre>// Final Global Variable which will expose the state.<br>// Should be outside of the class. <br><br>final connectivityStatusProviders = StateNotifierProvider((ref) {<br>  return ConnectivityStatusNotifier();<br>});</pre><blockquote>StateNotifierProvider is a provider that is used to listen to and expose a StateNotifier and is a Riverpods recommended solution for managing state which may change in reaction to users interaction.</blockquote><p>This connectivityStatusProvider will help us to listen to the state which is exposed by ConnectivityStateNotifier.</p><h3>UI</h3><p>Now let&#39;s create a UI where we can update the user about the connectivity changes that take place. Here I have used ConsumerWidget to get the notifier provider in the widget.</p><pre>class HomeScreen extends ConsumerWidget {<br>  const HomeScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br><strong>    var connectivityStatusProvider = ref.watch(connectivityStatusProviders);<br></strong>   <br>    return Scaffold(<br>        backgroundColor: Colors.black54,<br>        appBar: AppBar(<br>          title: const Text(<br>            &#39;Network Connectivity&#39;,<br>            style: TextStyle(<br>              color: Colors.white,<br>              fontSize: 20.0,<br>              fontWeight: FontWeight.bold,<br>            ),<br>          ),<br>        ),<br>        body: Center(<br>          child: Column(<br>            mainAxisAlignment: MainAxisAlignment.center,<br>            children: [<br>              const Text(<br>                &#39;Connectivity Status&#39;,<br>                style: TextStyle(<br>                  color: Colors.white,<br>                  fontSize: 20.0,<br>                  fontWeight: FontWeight.bold,<br>                ),<br>              ),<br>              Text(<br>               <strong> connectivityStatusProvider == ConnectivityStatus.isConnected<br>                    ? &#39;Is Connected to Internet&#39;<br>                    : &#39;Is Disconnected from Internet&#39;,</strong><br>                style: const TextStyle(<br>                  color: Colors.white,<br>                  fontSize: 20.0,<br>                ),<br>              )<br>            ],<br>          ),<br>        ));<br>  }<br>}</pre><h4>Show snackbar</h4><p>Now that we get the status of the connection let us show a snackbar which will update the user.</p><pre>   WidgetsBinding.instance.addPostFrameCallback((_) {<br>      ScaffoldMessenger.of(context).showSnackBar(<br>        SnackBar(<br>          content: Text(<br>            connectivityStatusProvider == ConnectivityStatus.isConnected<br>                ? &#39;Is Connected to Internet&#39;<br>                : &#39;Is Disconnected from Internet&#39;,<br>            style: const TextStyle(<br>              color: Colors.white,<br>              fontSize: 20.0,<br>            ),<br>          ),<br>          backgroundColor: connectivityStatusProvider ==<br>                  ConnectivityStatus.isConnected<br>              ? Colors.green<br>              : Colors.red,<br>        ),<br>      );<br>    });</pre><h4>Updating the main.dart.</h4><p>Whenever we use RiverPod we have wrap our app with ProviderScope so that widgets are able to read the Provider that we create.</p><pre>// main.dart<br><br>void main() {<br>  runApp(ProviderScope(child: NetworkConnectivity()));<br>}<br><br>class NetworkConnectivity extends StatelessWidget {<br>  const NetworkConnectivity({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: HomeScreen(),<br>    );<br>  }<br>}</pre><p>That&#39;s it. We have successfully created an application that updates the users when there is a change in the connectivity status of the device. Run the application on android, ios and try disconnecting and reconnecting the device to the internet.</p><p>Here is the complete code pushed to <a href="https://github.com/ShreeBhagwat/network_connectivity_riverpod">Github — network_connectivity_riverpod</a><strong><br>don’t forget to Like/Start the repo.</strong></p><blockquote><em>Thank You for reading my blog, if you have any doubts or recommendations please let me know in the comment section below. I would like to know what are the other way to globally listen to network connectivity.</em></blockquote><p>You have 50 Claps per day. Claps do Motivate us to keep writing. Gotta Use Them All</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Q6NW0VDfM1euwP7W16vK_A.gif" /></figure><figure><a href="https://www.buymeacoffee.com/codeaamy"><img alt="" src="https://cdn-images-1.medium.com/max/509/1*-1hjoCHabJ3X4ReQq5JPBQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbde21c187dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>