<?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 Richa Shah on Medium]]></title>
        <description><![CDATA[Stories by Richa Shah on Medium]]></description>
        <link>https://medium.com/@shahricha723?source=rss-92c9054cfbd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UtFdj9VkE3NNOhoCGIlOrQ.jpeg</url>
            <title>Stories by Richa Shah on Medium</title>
            <link>https://medium.com/@shahricha723?source=rss-92c9054cfbd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:28:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shahricha723/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[Problem-Solving Still Wins: Why AI Cannot Pick Your Architecture For You]]></title>
            <link>https://medium.com/@shahricha723/problem-solving-still-wins-why-ai-cannot-pick-your-architecture-for-you-3d44869be1e0?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d44869be1e0</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 14:36:22 GMT</pubDate>
            <atom:updated>2026-08-14T14:36:24.302Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How strong problem-solving skills help you choose the right design, flow, and architecture in the age of AI-assisted development</em></p><h3>Introduction</h3><p>AI coding assistants are fast. They can generate boilerplate, suggest fixes, scaffold a repository, and even write whole features from a prompt. But when a real problem appears — a flaky real-time connection, a stuck loader, a duplicated message, a logout that leaves a timer running — AI rarely solves it by accident. It solves it because a human asked the right question, narrowed the scope, and understood the real cause.</p><p>That is why problem-solving is still the core skill. AI is a multiplier, not a replacement. It amplifies the thinking you already have. If your problem-solving is weak, AI will help you build the wrong thing faster.</p><p>This post is about what good problem-solving looks like when designing architecture, flow, and systems in an AI-assisted world.</p><h3>1. AI Generates Answers. Problem-Solving Asks the Right Question.</h3><p>A prompt like “implement real-time chat with SignalR” will give you a working demo. It will not ask:</p><ul><li>What happens when the app goes to the background?</li><li>What happens when the token expires mid-session?</li><li>What happens if the same message arrives twice?</li><li>What happens when the user logs out but the reconnect timer keeps running?</li></ul><p>These are not implementation details. They are the difference between a demo and a product.</p><p>Good problem-solving starts before code. It defines the boundaries of the problem, the failure modes, and the success criteria. AI can then help inside those boundaries. Without those boundaries, AI gives you a plausible answer to an undefined question.</p><h3>2. Problem-Solving is Not Memorizing Patterns. It is Knowing When to Break Them.</h3><p>Architecture patterns are useful: BLoC, MVVM, Clean Architecture, microservices, monoliths, event sourcing. AI can list them and generate scaffold code for any of them.</p><p>But picking a pattern requires judgment. The same app might need:</p><ul><li>A <strong>singleton connection manager</strong> because one socket serves the whole app.</li><li><strong>Broadcast streams</strong> because multiple screens need the same server event.</li><li><strong>REST fallback</strong> because the socket cannot be the only source of truth.</li><li><strong>Feature BLoCs</strong> because state belongs close to the screen that uses it.</li></ul><p>None of these come from blindly applying BLoC or Clean Architecture. They come from analyzing the actual problem:</p><ul><li>Who owns the connection?</li><li>Who needs to listen?</li><li>What happens when it breaks?</li><li>How do we recover?</li></ul><p>Problem-solving turns a generic pattern into a specific design. AI can describe the pattern. Only you can decide how the pieces fit your constraints.</p><h3>3. Debugging is the Purest Form of Problem-Solving</h3><p>The hardest engineering work is not writing new code. It is fixing code that behaves in a way you did not expect. A stuck loader, a ghost subscription, a memory leak, a race condition — these are not solved by generating more code. They are solved by:</p><ol><li><strong>Reproducing the issue consistently.</strong></li><li><strong>Isolating the minimum path that triggers it.</strong></li><li><strong>Reading the actual state</strong> at each step, not the code you assumed was running.</li><li><strong>Forming a hypothesis</strong> about the root cause.</li><li><strong>Making the smallest change</strong> that tests that hypothesis.</li><li><strong>Verifying the fix</strong> and checking for regressions.</li></ol><p>AI can help at every step: write logs, search code, propose fixes. But the loop of observe → hypothesize → test → verify is a human skill. Without it, you end up applying random fixes until something changes, which often creates new bugs.</p><h3>4. Design Flows by Thinking in States and Transitions, Not Screens</h3><p>A common mistake is designing screens instead of flows. AI can generate a beautiful login screen or a dashboard, but it will not tell you how the app should behave when:</p><ul><li>Login succeeds but the next API call fails with a 401.</li><li>The user cancels authentication mid-flow.</li><li>A logout triggers token cleanup, socket disconnection, and navigation to login.</li><li>The loader must be hidden on every failure path, not just the happy path.</li></ul><p>Good problem-solving treats each flow as a state machine. Every action has states: loading, success, failure, cancellation, timeout, retry. The UI is just a reflection of those states.</p><p>When you model flows this way, AI becomes much more useful. You can ask it to implement a specific state transition with clear guards and error handling. The architecture becomes clearer because each state has a single owner.</p><h3>5. The Right Architecture Emerges From Constraints, Not Trends</h3><p>There is no perfect architecture. There is only the architecture that fits your constraints:</p><ul><li><strong>Real-time needs</strong> push you toward a persistent connection and broadcast streams.</li><li><strong>Offline-first needs</strong> push you toward local caching and optimistic UI patterns.</li><li><strong>Multi-tenant needs</strong> push you toward scoped subscriptions and context-aware state.</li><li><strong>High-reliability needs</strong> push you toward retries, fallbacks, idempotency, and observability.</li></ul><p>AI can generate code for any of these, but it cannot weigh the constraints for you. It does not know your team’s size, your release cadence, your user base, your observability budget, or your tolerance for complexity.</p><p>Problem-solving means translating business and operational constraints into technical boundaries. Once those boundaries are clear, AI can fill in the implementation.</p><h3>6. AI is Best at the Known. You Are Needed for the Unknown.</h3><p>AI is trained on code that already exists. It is excellent for:</p><ul><li>Boilerplate and scaffolding</li><li>Common algorithms and UI components</li><li>Refactoring and renaming</li><li>Explaining well-documented libraries</li></ul><p>It is weaker when:</p><ul><li>The bug has never been written about.</li><li>The product requirement is new.</li><li>Multiple subsystems interact in unexpected ways.</li><li>The failure only happens under real-world conditions.</li></ul><p>These are exactly the moments where problem-solving matters most. They require you to hold the whole system in your head, trace interactions, and make trade-offs that no training set can make for you.</p><h3>7. How to Strengthen Problem-Solving With AI</h3><p>The goal is not to avoid AI. The goal is to use AI in a way that makes you a sharper problem-solver.</p><h3>Ask “why” before asking “how”</h3><p>Before prompting for code, ask:</p><ul><li>What is the real problem?</li><li>What is the smallest change that would fix it?</li><li>What are the failure modes?</li></ul><h3>Use AI to explore, not decide</h3><p>Let AI generate options. Then evaluate them against your constraints. Ask it to compare trade-offs. Do not let it pick the architecture for you.</p><h3>Force yourself to explain the fix</h3><p>Before accepting an AI suggestion, explain why it works. If you cannot, you do not understand it yet. Ask for a simpler version or a breakdown.</p><h3>Keep the system small enough to reason about</h3><p>The bigger and more coupled the system, the harder it is to debug. Use AI to refactor into smaller, testable pieces with clear ownership. Good boundaries make problem-solving easier.</p><h3>Verify with tests, not trust</h3><p>A suggested fix is a hypothesis until a test proves it. Use AI to write tests, but run them. Add regression tests for bugs you fix. Over time, this builds confidence and documentation.</p><h3>8. A Simple Problem-Solving Process for Software Design</h3><p>Here is a process that works for architecture, flow, or debugging:</p><ol><li><strong>Define the problem in one sentence.</strong> If you cannot, you are not ready to solve it.</li><li><strong>List the constraints.</strong> Time, performance, reliability, team, platform, auth, offline behavior.</li><li><strong>Identify the actors and owners.</strong> Which component owns the connection? Which owns the state? Which owns the side effects?</li><li><strong>Map the happy path and the failure paths.</strong> Do not stop at success.</li><li><strong>Choose the smallest design that satisfies all paths.</strong> Avoid over-engineering.</li><li><strong>Implement and verify.</strong> Write tests, add telemetry, and observe real behavior.</li><li><strong>Refactor when new constraints appear.</strong> Architecture is not a one-time decision.</li></ol><p>AI can accelerate steps 5 and 6, but steps 1 through 4 are where the thinking happens.</p><h3>Conclusion</h3><p>AI makes writing code faster, but it does not remove the need to think. Problem-solving is the skill that turns AI output into reliable software. It helps you ask better questions, choose the right architecture, design flows that handle failure, and debug issues at their root instead of their symptoms.</p><p>The best engineers in an AI-assisted world will not be the ones who write the most prompts. They will be the ones who use AI to explore quickly, then apply judgment to decide what should actually be built.</p><p>If there is one skill to invest in today, it is problem-solving. Everything else — including AI — becomes more useful once you have it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d44869be1e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Real-Time in Flutter with SignalR: A Solution Blueprint]]></title>
            <link>https://medium.com/@shahricha723/scaling-real-time-in-flutter-with-signalr-a-solution-blueprint-2ab4966b8438?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab4966b8438</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 12:29:43 GMT</pubDate>
            <atom:updated>2026-08-13T12:29:43.844Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A pattern-first guide to building resilient, production-ready real-time mobile apps</em></p><h3>Introduction</h3><p>SignalR looks effortless in a demo. One hub, one client, instant updates. But mobile is not a browser tab that stays open on a stable desk. Networks change, apps background, tokens expire, and batteries run down. The gap between “works on my machine” and “works in production” is wide.</p><p>This post is a solution-oriented guide to closing that gap. It is not tied to any one app domain. Whether you are building live dashboards, notifications, monitoring, collaboration, or streaming data, the same problems show up again and again:</p><ul><li>How do you keep one socket alive for the whole app without coupling every screen to it?</li><li>How do you reconnect responsibly without draining the battery?</li><li>How do you handle auth expiry that happens while the socket is already open?</li><li>How do you keep the UI working when the socket is down?</li><li>How do you stop the same message from appearing twice?</li></ul><p>The answers below are general patterns, illustrated with fictional examples. No production endpoints, tokens, or business logic is shared.</p><h3>Why SignalR on Mobile is Harder Than It Looks</h3><p>SignalR abstracts transport negotiation, automatic reconnect, and hub method invocation. That is great for getting started, but mobile adds constraints the library does not solve for you:</p><ul><li><strong>App lifecycle:</strong> Backgrounding an app can kill or suspend the socket. When the user returns, the connection is gone.</li><li><strong>Network transitions:</strong> Wi-Fi to cellular, VPN on/off, captive portals, and DNS failures all break or stall sockets.</li><li><strong>Authentication expiry:</strong> A bearer token may expire while the app is backgrounded. The next hub call fails with a 401.</li><li><strong>Battery and data:</strong> Keeping a persistent connection open and retrying aggressively drains battery and consumes data.</li><li><strong>Multi-screen subscriptions:</strong> One screen unsubscribing must not tear down a channel another screen is still using.</li><li><strong>Ordering and deduplication:</strong> REST history and real-time pushes can overlap. The same payload can arrive twice.</li></ul><p>These are not library problems; they are architecture problems. The fix is disciplined lifecycle management, channel ownership, and a graceful degradation path to REST.</p><h3>Architecture: One Connection Manager, Many Subscribers</h3><p>The pattern that scales is a single manager that owns the transport, plus decoupled consumers that subscribe to named streams.</p><pre>SignalRHubManager (singleton)<br>  ├── owns HubConnection<br>  ├── owns connectionState stream<br>  ├── registers one handler per server event name<br>  └── fans events out to broadcast streams</pre><pre>Feature Consumer (BLoC / ViewModel / UseCase)<br>  ├── listens to a named broadcast stream<br>  ├── subscribes/unsubscribes to hub groups<br>  └── calls REST fallback when disconnected</pre><h3>Why a singleton transport layer?</h3><ul><li>One physical connection for the whole app.</li><li>One broadcast stream per server event name. Multiple screens can listen to the same event without registering duplicate handlers on the hub.</li><li>Subscriptions survive reconnects because the manager re-attaches handlers after connect(), not re-adds them.</li></ul><h3>Why broadcast streams?</h3><p>A server event is emitted once per method name on the hub. A broadcast StreamController lets many subscribers receive the same payload. When a consumer disposes, it cancels its subscription; the controller itself lives on.</p><h3>The Lifecycle Contract</h3><p>Real-time features fail silently when lifecycle boundaries are unclear. The contract should be enforced in every consumer:</p><p>Lifecycle EventActionConsumer initializesSubscribe to the relevant channelConsumer disposesUnsubscribe from the channelApp goes to backgroundKeep connection alive, pause dependent timersApp returns to foregroundRe-subscribe if still connected, otherwise call RESTHub reconnectsRe-subscribe all active channelsUser logs outUnsubscribe all + disconnect hubActive context changesUnsubscribe old context, subscribe new context</p><p>The two most common bugs are:</p><ol><li><strong>Forgetting to unsubscribe</strong> → the server keeps pushing to a dead consumer, wasting resources.</li><li><strong>Subscribing on every reconnect</strong> without checking → duplicate handlers and duplicated events.</li></ol><p>The manager solves the second problem by registering each handler exactly once per method name and re-attaching it after reconnect.</p><h3>Channel Subscriptions: Keys, Groups, and Arguments</h3><p>A subscription is identified by a channel key plus optional arguments. Think of a group as a logical room:</p><ul><li>DataFeed + tenantId → a tenant-scoped live feed</li><li>Notifications + userId → a user-scoped notification stream</li><li>Room + roomId → a room-scoped collaboration channel</li><li>Broadcast with no arguments → an unscoped global stream</li></ul><p>Subscriptions are per-consumer, but the connection is global. A consumer subscribes when it becomes active and unsubscribes when it disappears. Two consumers in the same room share the same broadcast stream; consumers in different rooms subscribe to different groups.</p><h3>The Reconnection Problem</h3><p>SignalR clients ship with withAutomaticReconnect(). That handles transient disconnects inside a single app session. It is not enough for mobile because:</p><ul><li>The OS may suspend the app long enough that automatic reconnect exhausts its retry budget.</li><li>A network interface change may not be noticed by the socket layer.</li><li>A token may expire and need a silent refresh before reconnect can succeed.</li></ul><p>The solution is a <strong>health-check watchdog</strong>: a conservative periodic timer that checks three things before each tick:</p><ol><li>Is the hub connected?</li><li>Is the device online?</li><li>Is a valid auth token present?</li></ol><p>If the device is online, the hub is disconnected, and a token is present, it attempts one reconnect. Then it waits again.</p><p>This is deliberately conservative:</p><ul><li>It does not retry forever in a tight loop.</li><li>It checks connectivity before attempting a doomed reconnect.</li><li>It stops when the user logs out.</li></ul><p>The watchdog is started on authenticated entry points and stopped on logout, app kill, or background.</p><h3>Authentication Handling: The 401 Edge Case</h3><p>A connection can succeed with a valid token, then later fail because the token expired or was revoked. The hub returns a 401. Reconnecting blindly just fails again.</p><p>A clean pattern is:</p><ol><li>Detect 401 in connect failure.</li><li>Attempt a silent token refresh.</li><li>If refresh succeeds, write the new token and retry connect().</li><li>If refresh fails, clear the session and redirect to login.</li></ol><p>This mirrors the HTTP interceptor pattern: refresh once, retry once, then give up cleanly.</p><h3>REST Fallback: The App Must Work Without the Socket</h3><p>SignalR should be the primary transport for updates, but the app cannot stop working when the socket is down. Every real-time consumer needs a REST fallback.</p><h3>Prefer SignalR when:</h3><ul><li>The hub is connected.</li><li>The user is on a screen that benefits from instant updates.</li></ul><h3>Fall back to REST when:</h3><ul><li>The hub is disconnected.</li><li>The screen loads for the first time.</li><li>The user pulls to refresh.</li><li>The app resumes from background.</li><li>Pagination is needed.</li><li>A mutation fails over SignalR.</li></ul><h3>Pattern: history first, then real-time</h3><p>On entering a live screen:</p><ol><li>Subscribe to the relevant hub group.</li><li>Load the initial page via REST.</li><li>Merge future SignalR payloads into the same list.</li></ol><p>This gives the user immediate data even if the socket is still connecting, and keeps data fresh once it is live.</p><h3>Pattern: resilient mutations</h3><p>If a user action must be persisted:</p><ol><li>Try the SignalR invocation first when connected.</li><li>If it fails or the hub is disconnected, POST to REST.</li><li>Deduplicate when the same payload eventually arrives from the hub.</li></ol><h3>Deduplication and Ordering</h3><p>Mixing REST and SignalR creates duplicates and ordering issues. A few rules keep the data clean:</p><ol><li><strong>Primary key deduplication:</strong> Every payload has a stable ID. The consumer stores a set of seen IDs and ignores duplicates.</li><li><strong>History gap fill:</strong> On reconnect, load REST history since the latest known timestamp. Merge by ID.</li><li><strong>No optimistic sends without local state:</strong> If a mutation was sent via REST, the same payload may arrive later from a reconnect. Deduplication handles it.</li><li><strong>Time-based ordering:</strong> Sort by server timestamp instead of arrival order.</li></ol><h3>UI State Rules for Real-Time Indicators</h3><p>Badges, counters, and banners need careful state handling:</p><ul><li><strong>Suppress the indicator while the user is already viewing the source screen.</strong> A counter should not flash if the user is already looking at the feed.</li><li><strong>Pause auto-refresh during filtering or pagination.</strong> Only append live updates when the list is at its initial state.</li><li><strong>Reset counts after acknowledgement.</strong> Use a fire-and-forget pattern for the acknowledgement so the UI does not block, then refresh on the next poll.</li><li><strong>Scope indicators to the active context.</strong> In multi-tenant or multi-project apps, an admin may see a global count while a regular user sees only the current context.</li></ul><h3>Testing What Actually Breaks</h3><p>Unit tests cannot simulate a backgrounded app switching networks, but they can cover the logic that matters:</p><ol><li><strong>Subscribe/unsubscribe lifecycle:</strong> Does the consumer subscribe on enter and unsubscribe on exit?</li><li><strong>Reconnect re-subscription:</strong> Does the consumer re-subscribe when HubConnectionState becomes connected again?</li><li><strong>API fallback on disconnect:</strong> Does the consumer fetch from REST when the hub is not connected?</li><li><strong>Pause/resume timer math:</strong> Do backgrounded timers resume from the correct elapsed time?</li><li><strong>Context switch:</strong> Does the consumer unsubscribe the old context and subscribe the new one?</li><li><strong>Logout cleanup:</strong> Does the manager stop the watchdog and close the connection?</li></ol><p>For integration testing, use real devices and toggle airplane mode at different lifecycle moments.</p><h3>Common Mistakes to Avoid</h3><ol><li><strong>Subscribing in every </strong><strong>initState or build without checking connection state.</strong> This stacks listeners and leaks subscriptions.</li><li><strong>Using SignalR for everything.</strong> Initial loads and pagination should use REST. SignalR is for updates, not bulk history.</li><li><strong>Retrying without checking connectivity.</strong> This fills logs and drains battery.</li><li><strong>Ignoring app lifecycle.</strong> A connection open in the background may be killed by the OS and leave the app in a confused state on resume.</li><li><strong>Forgetting to unsubscribe on logout.</strong> The next user may receive the previous user’s real-time events.</li><li><strong>Blocking the event queue on SignalR calls.</strong> Use unawaited() for non-critical actions, but keep await for mutations that need confirmation.</li></ol><h3>Conclusion</h3><p>SignalR is a powerful real-time transport, but a production mobile integration needs more than HubConnectionBuilder(). It needs lifecycle ownership, REST fallback paths, reconnect watchdogs, auth refresh handling, and deduplication discipline.</p><p>The pattern that works is simple: one connection manager, one broadcast stream per server event, decoupled consumers that subscribe and unsubscribe on lifecycle boundaries, and a clear rule that the app must keep working when the socket is down.</p><p>Invest in this architecture early. It is much cheaper than debugging ghost connections, duplicate messages, and stale indicators in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab4966b8438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Mobile Telemetry Layer with Azure Application Insights]]></title>
            <link>https://medium.com/@shahricha723/building-a-real-time-mobile-telemetry-layer-with-azure-application-insights-dd9b5ff14b48?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd9b5ff14b48</guid>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[azure-application-insight]]></category>
            <category><![CDATA[issue-tracking]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 12:03:21 GMT</pubDate>
            <atom:updated>2026-08-13T12:04:09.921Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to structured logging in Flutter apps for production observability</em></p><h3>Introduction</h3><p>Mobile apps fail in ways that are hard to reproduce: a call drops on a flaky Wi-Fi handoff, a BLE device setup freezes at the provisioning step, or a user is unexpectedly kicked back to the login screen with no visible error. Without telemetry, these issues become “it works on my device” mysteries. With structured telemetry, they become diagnosable events.</p><p>In this post, I’ll walk through how we built a centralized Azure Application Insights logging layer for a Flutter application that handles real-time communication, IoT device pairing, authentication, and push notifications. The goal was not just to collect crashes, but to trace entire user flows, identify failure patterns, and respond to issues before they become support tickets.</p><p>Why Azure Application Insights for Mobile?</p><p>Azure Application Insights is traditionally associated with backend services, but it works well for mobile clients too. It gives us:</p><ul><li><strong>Custom events</strong> for business/feature flows</li><li><strong>Exception telemetry</strong> for unhandled and caught errors</li><li><strong>User/session context</strong> to trace a single user’s journey</li><li><strong>KQL (Kusto Query Language)</strong> for powerful ad-hoc queries</li><li><strong>Live Metrics</strong> and dashboards for real-time monitoring</li></ul><p>For a Flutter app, the key is to abstract the SDK behind a clean domain layer so that feature code calls FeatureLogger.logX() instead of scattering SDK-specific code everywhere.</p><h3>The Architecture: Three Layers</h3><h3>1. Core Logger (HavnLogger)</h3><p>At the bottom is a thin wrapper around the Application Insights SDK. It handles:</p><ul><li>Initialization with the correct instrumentation key per environment (dev, QA, beta, production)</li><li>Setting the user ID and email after login</li><li>Clearing user identity on logout for privacy and data hygiene</li><li>A single log() method that accepts:</li><li>eventName</li><li>feature</li><li>status (started, success, failure, exception)</li><li>step</li><li>properties map</li><li>errorMessage / errorCode</li></ul><p>This keeps the SDK dependency in one place and makes the rest of the app SDK-agnostic.</p><h3>2. Feature Loggers</h3><p>Each major feature has its own logger that provides typed methods and manages correlation IDs. This is where the real value lives.</p><h4>Example: Login Logger</h4><p>Authentication is a multi-step flow. Instead of one generic “login failed” event, we log each step:</p><ul><li>msal_login_started</li><li>msal_pca_creation_started</li><li>msal_pca_creation_success / msal_pca_creation_failed</li><li>msal_token_acquire_started</li><li>msal_token_acquire_success / msal_token_acquire_failed</li><li>msal_user_preference_started</li><li>msal_user_preference_success / msal_user_preference_failed</li><li>msal_login_complete</li><li>msal_logout_started / msal_logout_complete</li><li>msal_auto_logout (for session expiry)</li></ul><p>Each step carries a flowId (a UUID generated at the start of the flow), so we can reconstruct the entire login journey for a single user.</p><h4>Example: Real-Time Communication Logger</h4><p>For WebRTC and SignalR flows, we log:</p><ul><li>Hub connection lifecycle (connecting, connected, reconnecting, reconnected, disconnected)</li><li>Verto protocol events (INVITE sent/received, ANSWER sent/received)</li><li>SDP offers and answers (truncated for size)</li><li>ICE candidate gathering</li><li>Call start, answer, end, and audio route changes</li><li>Health-check watchdog reconnects</li></ul><p>A correlation flowId lets us trace a single call from the moment the user taps &quot;Call&quot; through ICE negotiation to the final hangup.</p><h4>Example: Device Setup Logger</h4><p>BLE device pairing is fragile. We log every UI step:</p><ol><li>Room selection</li><li>Bluetooth check</li><li>BLE scan</li><li>Device connection</li><li>Provisioning check</li><li>Wi-Fi scan and selection</li><li>Wi-Fi credentials write</li><li>IoT provisioning</li><li>Motion detection verification</li><li>Setup completion</li></ol><p>Each step has a step_number, so we can reconstruct the exact sequence that led to a failure.</p><h4>Example: Push Notification Logger</h4><p>Push token lifecycle is logged on:</p><ul><li>FCM token fetch (login)</li><li>FCM token delete (logout)</li><li>iOS APNS token retrieval</li><li>Success and failure paths with platform and error code</li></ul><p>This helps diagnose why some users stop receiving notifications after an app update or device migration.</p><h3>3. Automatic Interceptors</h3><p>A Dio interceptor logs HTTP errors automatically:</p><ul><li>Method, URL, status code</li><li>Error code and message</li><li>User ID and session ID</li><li>Configurable URL exclusions for noisy endpoints</li></ul><p>This catches API failures without requiring explicit logging calls in every repository.</p><h3>Centralized Constants</h3><p>All event names and property keys live in a single LoggerConstant file. This prevents:</p><ul><li>Typos in event names</li><li>Inconsistent property keys</li><li>Refactoring pain</li><li>Duplicate or nearly-identical events</li></ul><p>The constant file is organized by feature and includes both event names and property keys. The result is type-safe telemetry.</p><pre>HavnLogger.log(<br>  eventName: LoggerConstant.msalLoginStarted,<br>  feature: LogFeature.msalLogin,<br>  status: LogStatus.started,<br>  step: LogStep.tokenAcquire,<br>  properties: {<br>    LoggerConstant.propSiteId: siteId,<br>    LoggerConstant.propDeviceId: deviceId,<br>  },<br>);</pre><h3>Real-World Scenarios</h3><h3>Scenario 1: “Calls Drop for Some Users”</h3><p>A support ticket says calls drop after 30 seconds for a subset of users. With call flow logs, we can query:</p><pre>customEvents<br>| where customDimensions.feature == &quot;webrtc_call&quot;<br>| where customDimensions.correlation_id == &quot;&lt;callFlowId&gt;&quot;<br>| project timestamp, name,<br>          customDimensions.step,<br>          customDimensions.status,<br>          customDimensions.error_message<br>| order by timestamp asc</pre><p>We can see whether the drop happened during SDP negotiation, ICE candidate gathering, or after the call was established. Often the issue is a missing relay ICE candidate on corporate networks.</p><h3>Scenario 2: “Device Setup Gets Stuck”</h3><p>A user reports the device setup screen never finishes. With setup step logs:</p><pre>customEvents<br>| where customDimensions.feature == &quot;device_setup&quot;<br>| where customDimensions.correlation_id == &quot;&lt;flowId&gt;&quot;<br>| project timestamp, name,<br>          tolong(customDimensions.step_number),<br>          customDimensions.step,<br>          customDimensions.status,<br>          customDimensions.error_message<br>| order by tolong(customDimensions.step_number) asc</pre><p>We can see exactly which step (e.g., motion detection or Wi-Fi write) stalled and what the error was.</p><h3>Scenario 3: “Users Are Logged Out Unexpectedly”</h3><p>Auto-logout events are logged with the reason (401 expiry, token refresh failure, SignalR token failure). Querying:</p><pre>customEvents<br>| where name == &quot;msal_auto_logout&quot;<br>| where timestamp &gt; ago(7d)<br>| summarize count() by tostring(customDimensions.reason)</pre><p>This tells us whether users are being kicked out because of session expiry, network issues, or authentication problems.</p><h3>Scenario 4: “Push Notifications Stop Arriving”</h3><p>For notification issues, we query token fetch/delete events:</p><pre>customEvents<br>| where name in (&quot;fcm_token_fetch_failed&quot;, &quot;fcm_token_delete_failed&quot;)<br>| where timestamp &gt; ago(24h)<br>| project timestamp, customDimensions.user_id,<br>          customDimensions.platform,<br>          customDimensions.error_message,<br>          customDimensions.error_code<br>| order by timestamp desc</pre><p>Common findings include apns-token-not-set on iOS or token deletion failures during logout.</p><h3>Scenario 5: “API Errors Spike After a Release”</h3><p>The HTTP interceptor logs all failed requests. We can group by endpoint and status code:</p><pre>customEvents<br>| where name == &quot;api_error&quot;<br>| where timestamp &gt; ago(24h)<br>| summarize count() by tostring(customDimensions.url),<br>                       toint(customDimensions.status_code)<br>| order by count_ desc</pre><p>This quickly identifies if a specific endpoint started failing after a deployment.</p><h3>Best Practices We Followed</h3><ol><li><strong>Use correlation IDs for multi-step flows</strong><br>Every flow gets a UUID. Reconstruction is trivial with a single KQL query.</li><li><strong>Truncate large payloads</strong><br>SDP descriptions and ICE candidate lists are truncated (e.g., first 500 or 2000 chars) to avoid ingestion limits and cost surprises.</li><li><strong>Log early, log at every branch</strong><br>Don’t just log success and failure. Log the start of each step so you know which path was taken.</li><li><strong>Fire-and-forget logging where safe</strong><br>Use unawaited() for logging calls that should not block the UI or BLoC event queue. Critical paths (like logout) can still use await.</li><li><strong>Clear user identity on logout</strong><br>Always clear the user ID and email so post-logout events are not attributed to the previous user.</li><li><strong>Environment-aware keys</strong><br>Use different Application Insights instrumentation keys for dev, QA, beta, and production. The correct key is selected automatically based on the build flavor.</li><li><strong>Keep event and property names in constants</strong><br>A single source of truth prevents subtle bugs and makes renaming safe.</li></ol><h3>What We Avoided</h3><ul><li><strong>Wrapper services</strong>: We log directly through the core logger. Extra wrappers add boilerplate and make stack traces harder to follow.</li><li><strong>Per-screen logging</strong>: This creates noise. We log feature flows and errors, not every widget build.</li><li><strong>Logging sensitive data</strong>: Tokens, full SDP payloads, and personal identifiers are truncated or omitted.</li><li><strong>Blocking awaits on non-critical telemetry</strong>: Logging should not slow down the user flow.</li></ul><h3>Impact</h3><p>After adding structured telemetry, the time to diagnose production issues dropped significantly. Instead of asking users to reproduce steps, we can now:</p><ul><li>Reconstruct a failing flow from event sequence</li><li>Correlate failures with app version, platform, and user region</li><li>Spot regressions within minutes of a release</li><li>Measure success rates of critical flows (login, setup, calls, Wi-Fi change)</li></ul><p>Telemetry is not just for debugging crashes; it becomes a product health dashboard.</p><h3>Conclusion</h3><p>Azure Application Insights, combined with a disciplined logging architecture in Flutter, gives mobile teams production-grade observability. The key is structure: typed feature loggers, correlation IDs, centralized constants, automatic interceptors, and environment-aware configuration.</p><p>If you are building a Flutter app with real-time features, IoT pairing, or complex authentication flows, consider investing in this kind of telemetry early. The upfront cost is small compared to the hours saved diagnosing “impossible to reproduce” bugs later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd9b5ff14b48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Crystal Clear Voice Calls: How We Solved Echo Cancellation and Bluetooth Routing in…]]></title>
            <link>https://medium.com/@shahricha723/building-crystal-clear-voice-calls-how-we-solved-echo-cancellation-and-bluetooth-routing-in-3a2a37574f0b?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a2a37574f0b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[voip]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 04:51:09 GMT</pubDate>
            <atom:updated>2026-06-09T04:51:09.718Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Crystal Clear Voice Calls: How We Solved Echo Cancellation and Bluetooth Routing in Flutter WebRTC</h3><p><em>A deep dive into the technical challenges that make VoIP seem simple but hide complex cross-platform audio engineering.</em></p><p>When a user taps the “Call” button on their phone, they expect one thing: to hear the other person clearly without their own voice echoing back. Simple, right?</p><p>Behind the scenes, it’s anything but. Coordinating WebRTC audio streams, operating system frameworks, Bluetooth hardware, and device-specific quirks across Android and iOS requires obsessive attention to detail.</p><p>We recently completed a major overhaul of our voice calling infrastructure to solve persistent echo, Bluetooth routing failures, and audio configuration issues that plagued our Flutter WebRTC implementation. Here’s what we learned — and how we fixed it.</p><h3>The Echo Problem: Why WebRTC Alone Wasn’t Enough</h3><p>Echo is the nemesis of VoIP. Users complain about hearing their own voice bouncing back, and engineering teams scratch their heads wondering why WebRTC’s built-in echo cancellation isn’t working.</p><p>We thought we understood the problem. Activate WebRTC’s audio constraints, enable Acoustic Echo Cancellation (AEC), and you’re done.</p><p>We were wrong.</p><h3>What We Discovered During Testing</h3><p>Our testing revealed a brutal reality:</p><ul><li><strong>Google Pixel devices</strong> worked reasonably well with flutter WebRTC defaults</li><li><strong>Samsung, OnePlus, Xiaomi, and Realme devices</strong> continued producing echo despite WebRTC being enabled</li><li><strong>Speakerphone mode</strong> could reintroduce echo even after successful setup</li><li><strong>Bluetooth audio routes</strong> behaved completely differently from wired or built-in speaker output</li></ul><p>The problem wasn’t WebRTC. The problem was that many Android OEMs never activate hardware-level Acoustic Echo Cancellation (AEC) unless the operating system is explicitly configured for voice communication mode.</p><h3>The Two-Layer Solution: WebRTC + Native Platform Audio</h3><p>We implemented a dual-layer approach that addresses both software and hardware layers:</p><h3>Layer 1: WebRTC Audio Processing</h3><p>When acquiring the microphone stream via getUserMedia(), we explicitly enable all supported audio processing capabilities:</p><ul><li>Echo Cancellation</li><li>Auto Gain Control (AGC)</li><li>Noise Suppression</li><li>High-Pass Filtering</li><li>Delay-Agnostic Echo Cancellation</li><li>Typing Noise Detection</li><li>Google Audio Processing Pipelines</li></ul><p>This provides WebRTC’s software-level protection against feedback and environmental noise. But as we discovered, software alone wasn’t sufficient.</p><h3>Layer 2: Native Platform Audio Configuration</h3><p>The real breakthrough came when we enforced platform-specific audio configurations.</p><h4>Android: The Critical Sequence</h4><p>On Android, the magic happens with AudioManager.MODE_IN_COMMUNICATION. But here&#39;s the catch—<strong>the order matters significantly</strong>.</p><p>Our final sequence:</p><ol><li>Configure communication audio mode</li><li>Request exclusive voice-call audio focus</li><li>Acquire microphone via getUserMedia()</li><li>Start call audio routing</li><li><strong>Re-apply communication mode after every route change</strong></li></ol><p>Without this exact sequence, many OEM devices never activated hardware AEC.</p><h4>iOS: The Elegant Path</h4><p>iOS was far cleaner. Using:</p><pre>AVAudioSession.Category.playAndRecord<br>AVAudioSession.Mode.voiceChat</pre><p>automatically enables Apple’s hardware echo cancellation and voice processing pipeline. Combined with WebRTC audio constraints, this delivers reliable echo-free communication across most iOS devices.</p><h3>The Evidence: Why Both Layers Matter</h3><p>Scenario WebRTC Only Native Only Combined Pixel Devices ✅ ✅ ✅ Samsung / OnePlus / Xiaomi ❌ ❌ ✅ Speaker Mode ❌ ❌ ✅ Bluetooth Calls ⚠️ ❌ ✅</p><p>The conclusion was inescapable: <strong>reliable echo cancellation requires both layers working in concert.</strong></p><h3>The Android Earpiece Bug: A Timing Issue</h3><p>Here’s a problem that took weeks to debug.</p><p>Some Android devices routed audio to the speaker during the first call, even when the UI clearly indicated earpiece mode was selected. The behavior was inconsistent and nearly impossible to reproduce reliably.</p><h3>Root Cause</h3><p>We finally found it: MODE_IN_COMMUNICATION was being applied <em>too late</em>.</p><ul><li>WebRTC had already created its audio track</li><li>Android had initialized the route using standard media audio behavior</li><li>The earpiece setting was lost</li></ul><h3>The Fix</h3><p>We introduced a <strong>pre-call audio preparation phase</strong>. Before requesting microphone access, the application now:</p><ol><li>Switches to communication mode</li><li>Requests audio focus</li><li>Prepares voice communication routing</li></ol><p>Result: First calls now consistently start using the intended earpiece route.</p><p>This small timing change eliminated an entire class of user complaints.</p><h3>Bluetooth: From Whitelist to Universal Detection</h3><p>Bluetooth support was another major source of frustration.</p><h3>The Old Approach (That Failed)</h3><p>We started with a whitelist strategy, checking for known device names:</p><ul><li>boAt</li><li>JBL</li><li>Sony</li><li>Realme</li><li>(And a growing list of others)</li></ul><p>This worked until someone connected a brand we hadn’t anticipated.</p><h3>The New Approach (That Scales)</h3><p>We flipped the logic entirely. Any audio output that is <strong>not</strong>:</p><ul><li>Speaker</li><li>Receiver</li><li>Phone</li><li>Earpiece</li></ul><p>…is automatically classified as a Bluetooth device.</p><p>This provides <strong>universal compatibility</strong> with:</p><ul><li>Sony, JBL, boAt, Realme</li><li>Pixel Buds</li><li>Car Bluetooth systems</li><li>Future devices we’ve never heard of</li></ul><p>No more updates needed for new hardware.</p><h3>Bluetooth SCO: Making Headsets Actually Work</h3><p>Detecting a Bluetooth device is only half the battle. The operating system must also route <em>call audio</em> through it.</p><h3>The Problem</h3><p>Even when a Bluetooth device was connected and detected:</p><ul><li>Audio frequently remained on speaker</li><li>Calls sometimes continued through the earpiece</li><li>Bluetooth microphones weren’t always used</li></ul><p>Why? Because Android voice communication requires an active <strong>Bluetooth SCO (Synchronous Connection Oriented) connection</strong>. Without it:</p><ul><li>The headset appears connected ✓</li><li>Media audio works ✓</li><li>Voice call audio doesn’t route ✗</li></ul><h3>The Solution</h3><p>We implemented native SCO lifecycle management:</p><p><strong>When Bluetooth is Selected:</strong></p><pre>startBluetoothSco();<br>setBluetoothScoOn(true);</pre><p><strong>When Bluetooth is Removed:</strong></p><pre>stopBluetoothSco();<br>setBluetoothScoOn(false);</pre><p>This ensures proper routing for both playback and microphone input.</p><h3>Automatic Recovery: When Users Disconnect</h3><p>Real world usage is messy. Users:</p><ul><li>Turn off earbuds mid-call</li><li>Walk out of Bluetooth range</li><li>Lose connectivity</li></ul><p>Previously, the app could become stuck in an invalid audio state.</p><h3>New Behavior</h3><p>When a Bluetooth device disappears:</p><ol><li>Device change listener detects removal</li><li>Audio automatically switches back to earpiece mode</li><li>UI updates immediately</li><li><strong>Call continues uninterrupted</strong></li></ol><p>Testing confirmed reliable recovery on Samsung, OnePlus, Realme, and Pixel devices.</p><p>Users barely notice their headset died.</p><h3>The Speakerphone Echo Trap</h3><p>One subtle issue haunted several Android OEM devices.</p><p>Toggle speaker mode, and suddenly echo returns. Users would:</p><ol><li>Start a call</li><li>Enable speakerphone</li><li>Disable speakerphone</li><li>Hear their own voice echoing back</li></ol><p>Some manufacturers silently reset communication audio settings whenever the output route changes. Our fix: after <strong>every route change</strong>, we now:</p><ul><li>Re-apply MODE_IN_COMMUNICATION</li><li>Restore voice communication audio focus</li><li>Adjust volume appropriately</li></ul><p>This guarantees hardware echo cancellation remains active throughout the call lifecycle.</p><h3>The Remaining iOS Challenge</h3><p>While Android behavior is now largely stabilized, iOS presents one persistent issue.</p><h3>BLE Disconnect Detection</h3><p>The Flutter WebRTC device-change callback doesn’t consistently fire when a Bluetooth device disconnects during an active call.</p><p><strong>Current behavior:</strong></p><ul><li>iOS correctly reroutes audio internally ✓</li><li>The call continues normally ✓</li><li>Flutter UI state may become outdated ✗</li></ul><p>This appears to be a limitation within the current Flutter WebRTC implementation. We’re investigating:</p><ul><li>Native AVAudioSession route-change monitoring</li><li>Flutter plugin updates</li><li>Future WebRTC package improvements</li></ul><h3>Results: Validation Across Devices</h3><p>Our solution was validated across multiple devices and routing scenarios:</p><p>Google Pixel ✅ ✅ ✅ ✅ Samsung Galaxy ✅ ✅ ✅ ✅ OnePlus ✅ ✅ ✅ ✅ Realme ✅ ✅ ✅ ✅ iPhone 13 Pro ✅ ✅ ✅ ⚠</p><h3>External Hardware: The Next Frontier</h3><p>We also focused on interoperability with external communication hardware (HAVN devices).</p><p><strong>Successful scenarios:</strong></p><ul><li>Android → HAVN Device: Echo cancellation works correctly with stable behavior in both earpiece and Bluetooth modes</li></ul><p><strong>Open issues:</strong></p><ul><li>HAVN Device → Android: Echo remains present on the phone side</li><li>iOS → HAVN Device: Echo can occur on both device speaker and mobile phone sides</li></ul><p>These remaining cases suggest the issue originates from the hardware audio path rather than our mobile application.</p><h3>Recommendations for Hardware Teams</h3><p>The mobile application now enforces platform-level hardware AEC on both Android and iOS. To eliminate remaining device-to-phone echo scenarios, hardware teams should consider:</p><ol><li><strong>Device-Side Acoustic Echo Cancellation</strong> — Implement firmware-level AEC to remove speaker output from microphone capture</li><li><strong>Better Acoustic Isolation</strong> — Reduce physical coupling between device speaker and microphone through hardware design</li><li><strong>Adaptive Playback Volume</strong> — Lower speaker output while the local microphone is active to reduce acoustic feedback</li></ol><h3>The Bigger Picture: Echo Cancellation Isn’t One Thing</h3><p>This is the core lesson we learned: <strong>echo cancellation is not a feature. It’s a system.</strong></p><p>Building reliable VoIP requires coordinating:</p><ul><li>WebRTC audio processing</li><li>Android AudioManager configuration</li><li>iOS AVAudioSession behavior</li><li>Bluetooth SCO routing</li><li>Route-change handling</li><li>Device-specific hardware characteristics</li></ul><p>Missing any single piece, and the whole thing falls apart.</p><h3>Key Takeaways</h3><ol><li><strong>Trust but verify</strong> — Don’t assume WebRTC’s defaults work everywhere. Test on real devices with OEM customizations.</li><li><strong>Platform matters</strong> — Android and iOS require completely different approaches to audio configuration. Treat them as distinct problems.</li><li><strong>Timing is everything</strong> — The order of operations (MODE_IN_COMMUNICATION before getUserMedia) can make or break echo cancellation.</li><li><strong>Test the real world</strong> — Users don’t toggle speaker mode in controlled lab conditions. They disconnect Bluetooth mid-conversation. Build for messy reality.</li><li><strong>Hardware is part of the system</strong> — Some problems can’t be solved in software. Communicate findings back to hardware teams.</li></ol><h3>What’s Next?</h3><p>The current architecture provides a strong foundation for production-grade voice communication. While some hardware-specific scenarios remain under investigation, we’ve achieved:</p><ul><li>✅ Significantly improved call quality across Android and iOS</li><li>✅ More reliable Bluetooth routing</li><li>✅ Consistent behavior across device manufacturers</li><li>✅ Automatic recovery from connectivity issues</li></ul><p>Building VoIP is humbling work. Every release surfaces edge cases you didn’t anticipate. But each fix moves us closer to that ideal: users tap “Call,” and the voice they hear is crystal clear.</p><p><em>Have you encountered similar challenges building VoIP applications? Share your experiences in the comments below. And if you’re wrestling with echo issues in your own WebRTC implementation, the two-layer approach outlined here might be the breakthrough you need.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a2a37574f0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Kotlin Codebase with Detekt: Integration + Custom Rules]]></title>
            <link>https://medium.com/@shahricha723/supercharge-your-kotlin-codebase-with-detekt-integration-custom-rules-a0a434d7d83c?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0a434d7d83c</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[coding-standards]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[lint]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 10:38:20 GMT</pubDate>
            <atom:updated>2025-07-30T10:38:20.879Z</atom:updated>
            <content:encoded><![CDATA[<p>When working on large Kotlin projects, maintaining code quality, readability, and consistency becomes non-negotiable. That’s where <strong>Detekt</strong> comes in.</p><p><strong>Detekt</strong> is a powerful <strong>static code analysis tool</strong> for Kotlin that helps you detect <strong>code smells</strong>, enforce <strong>coding standards</strong>, and keep your project clean — just like <strong>Lint</strong> does for XML and Java, but tailored for Kotlin.</p><p>In this post, we’ll walk through:</p><ul><li>What Detekt is and why it’s helpful</li><li>How to integrate Detekt into an Android project</li><li>How to configure and run Detekt</li><li>How to <strong>write custom Detekt rules</strong> to enforce project-specific standards</li><li>How to test and use your custom rule in production</li></ul><h3>🔍 What is Detekt?</h3><blockquote><em>“Static code analysis for Kotlin.” — </em><a href="https://github.com/detekt/detekt"><em>Detekt GitHub</em></a></blockquote><p>Detekt scans your codebase for:</p><ul><li>Complexity</li><li>Naming issues</li><li>Bad practices</li><li>Potential bugs</li><li>Style violations</li><li>…and more</li></ul><p>Unlike <strong>Javadoc</strong> or <strong>Checkstyle</strong>, Detekt was built for Kotlin from the ground up. It offers <strong>out-of-the-box rule sets</strong> and allows <strong>custom rules</strong>, <strong>baseline support</strong>, <strong>IDE integration</strong>, and <strong>CI/CD integration</strong> via GitHub Actions, SonarQube, and more.</p><h3>🛠️ Step-by-Step Integration in Android Studio</h3><h3>1. Add Detekt to build.gradle</h3><h4>Project-level build.gradle:</h4><pre>classpath &quot;io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.22.0&quot;</pre><h4>App-level build.gradle:</h4><pre>apply plugin: &quot;io.gitlab.arturbosch.detekt&quot;</pre><p>Then sync the project.</p><blockquote><em>⚠️ </em><strong><em>Note:</em></strong><em> Detekt requires Gradle </em><strong><em>6.1+</em></strong></blockquote><h3>🧪 Run Detekt</h3><p>To run Detekt and generate your first report:</p><pre>./gradlew detekt</pre><p>This analyzes your code using Detekt’s default configuration.</p><h3>⚙️ Customize Configuration</h3><p>Generate a configuration file to fine-tune the rules:</p><pre>./gradlew detektGenerateConfig</pre><p>It creates detekt.yml in your config/detekt/ directory.</p><p>Inside detekt.yml, enable or disable rules. For example:</p><pre>comments:<br>  active: true<br>  excludes: &quot;**/test/**,**/androidTest/**&quot;</pre><h3>🧯 Add a Baseline (Optional for Legacy Projects)</h3><p>To suppress existing issues in large codebases:</p><pre>./gradlew detektBaseline</pre><p>Then add it to your build.gradle:</p><pre>detekt {<br>    baseline = file(&quot;config/detekt/baseline.xml&quot;)<br>}</pre><h3>🧰 Configuring Detekt in build.gradle</h3><p>Here’s a sample setup for more control:</p><pre>detekt {<br>    config = files(&quot;$rootDir/config/detekt/detekt.yml&quot;)<br>    buildUponDefaultConfig = false<br>    parallel = true<br>    allRules = false<br>    source = files(&quot;src/main/kotlin&quot;)<br>    ignoreFailures = false<br>}</pre><h3>✨ Creating a Custom Rule</h3><p>Sometimes the default rules aren’t enough — say, banning deprecated APIs like <strong>Kotlin Android Extensions</strong>. Here’s how to add your <strong>own Detekt rule</strong>.</p><h3>Step 1: Add Dependencies to Your customRules Module</h3><pre>// build.gradle of customRules module<br>compileOnly &quot;io.gitlab.arturbosch.detekt:detekt-api:1.17.1&quot;<br>testImplementation &quot;io.gitlab.arturbosch.detekt:detekt-test:1.17.1&quot;<br>testImplementation &quot;org.assertj:assertj-core:3.19.0&quot;<br>testImplementation &#39;junit:junit:4.13.2&#39;</pre><h3>Step 2: Write a Custom Rule</h3><pre>class NoSyntheticImportRule : Rule() {<br>  override val issue = Issue(<br>    &quot;NoSyntheticImport&quot;,<br>    Severity.Maintainability,<br>    &quot;Don’t use Kotlin Synthetics, they are deprecated.&quot;,<br>    Debt.TWENTY_MINS<br>  )</pre><pre>  override fun visitImportDirective(importDirective: KtImportDirective) {<br>    val import = importDirective.importPath?.pathStr<br>    if (import?.contains(&quot;kotlinx.android.synthetic&quot;) == true) {<br>      report(<br>        CodeSmell(issue, Entity.from(importDirective),<br>        &quot;Importing &#39;$import&#39; which is a Kotlin Synthetics import.&quot;)<br>      )<br>    }<br>  }<br>}</pre><h3>Step 3: Register RuleSetProvider</h3><pre>class CustomRuleSetProvider : RuleSetProvider {<br>  override val ruleSetId = &quot;synthetic-import-rule&quot;</pre><pre>  override fun instance(config: Config): RuleSet =<br>      RuleSet(ruleSetId, listOf(NoSyntheticImportRule()))<br>}</pre><p>Then, in src/main/resources/META-INF/services/io.gitlab.arturbosch.detekt.api.RuleSetProvider, add:</p><pre>com.yourpackage.CustomRuleSetProvider</pre><h3>🧪 Test Your Rule</h3><pre>class NoSyntheticImportTest {<br>  @Test<br>  fun noSyntheticImports() {<br>    val findings = NoSyntheticImportRule().lint(&quot;&quot;&quot;<br>      import kotlinx.android.synthetic.main.activity_main.*<br>    &quot;&quot;&quot;.trimIndent())</pre><pre>    assertThat(findings).hasSize(1)<br>    assertThat(findings[0].message).contains(&quot;Kotlin Synthetics&quot;)<br>  }<br>}</pre><p>Run the test — ✅ Your rule is live!</p><h3>📦 Use Your Custom Rule in Your Project</h3><h3>In app/build.gradle:</h3><pre>dependencies {<br>  detekt &quot;io.gitlab.arturbosch.detekt:detekt-cli:1.17.1&quot;<br>  detekt project(&quot;:customRules&quot;)<br>}</pre><h3>In detekt.yml:</h3><pre>synthetic-import-rule:<br>  active: true<br>  NoSyntheticImportRule:<br>    active: true</pre><p>Run Detekt again:</p><pre>./gradlew detekt</pre><p>Boom 💥 — Your rule flags synthetic imports!</p><h3>🚀 Wrapping Up</h3><p>You’ve just:<br> ✅ Integrated Detekt into Android Studio<br> ✅ Customized your Detekt configuration<br> ✅ Written, tested, and integrated a custom rule<br> ✅ Enforced Kotlin coding best practices automatically</p><p><strong>Static analysis</strong> is one of the easiest ways to improve code quality and catch issues before runtime — and with <strong>Detekt</strong>, it’s beautifully Kotlin-native.</p><p>📌 <strong>Sample project:</strong> <a href="https://github.com/nagusmart/detekt_sample_app">GitHub — detekt_sample_app</a></p><p>💬 Got feedback or questions? Drop them in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0a434d7d83c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dokka — The Kotlin & Java Documentation Tool You Should Be Using]]></title>
            <link>https://medium.com/@shahricha723/dokka-the-kotlin-java-documentation-tool-you-should-be-using-154ceb7e6da2?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/154ceb7e6da2</guid>
            <category><![CDATA[dokka]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[codequalityjava]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 10:34:05 GMT</pubDate>
            <atom:updated>2025-07-30T10:34:05.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dokka — The Kotlin &amp; Java Documentation Tool You Should Be Using</h3><p>In the world of software development, good documentation is not a luxury — it’s a necessity. Whether you’re onboarding a new developer or maintaining your codebase months later, clear and consistent documentation saves time and reduces confusion.</p><p>If you’re a Kotlin developer, you’ve probably wondered: <strong>Is there a Kotlin equivalent to Javadoc?</strong><br> Well, the answer is <strong>yes</strong>, and it’s called <strong>Dokka</strong>.</p><h3>💡 What is Dokka?</h3><p>Dokka is a documentation engine developed by <strong>JetBrains</strong>, the creators of Kotlin. Much like Javadoc for Java, <strong>Dokka</strong> helps you generate structured documentation for your code — but it goes one step further:</p><p>✅ Supports both <strong>Kotlin and Java</strong><br> ✅ Outputs documentation in <strong>multiple formats</strong>: HTML, Markdown (GFM), Javadoc-style, Jekyll, etc.<br> ✅ Parses <strong>KDoc</strong> comments in Kotlin files and <strong>Javadoc-style</strong> comments in Java files</p><blockquote><em>In short, </em><strong><em>Dokka bridges the documentation gap</em></strong><em> between Kotlin and Java in a seamless way.</em></blockquote><h3>🎯 Why Use Dokka?</h3><p>Great documentation has a few common characteristics:</p><ul><li>✅ Understandable and readable</li><li>✅ Accurate and up-to-date</li><li>✅ Simple, concise, and properly formatted</li><li>✅ Descriptive of parameters, receivers, links, and functionality</li></ul><p><strong>Dokka encourages all of this</strong> by integrating tightly with Kotlin’s official documentation style (KDoc), and generating static documentation that’s easy to publish and share.</p><h3>⚙️ How to Set Up Dokka in Your Android Project</h3><p>Let’s go step-by-step to integrate Dokka in an Android (or Kotlin-based) project.</p><h3>🔧 1. Add Dokka Dependency in Project-level build.gradle</h3><pre>buildscript {<br>    ext.dokka_version = &#39;1.7.20&#39; // Use the latest stable version if available<br>    dependencies {<br>        classpath &quot;org.jetbrains.dokka:dokka-gradle-plugin:$dokka_version&quot;<br>    }<br>}</pre><h3>📦 2. Apply Dokka Plugin in App-level build.gradle</h3><pre>apply plugin: &#39;org.jetbrains.dokka&#39;</pre><p>This enables Dokka for your module.</p><h3>📁 3. (Optional) Add Secrets Block (if needed)</h3><p>If you’re using Dokka in a project that handles secrets (e.g., via app.properties), you may need this block inside the android {} section of your build.gradle:</p><pre>android {<br>    ...<br>    secrets {<br>        defaultPropertiesFileName = &#39;app.properties&#39;<br>    }<br>}</pre><blockquote><em>You can skip this step if your project doesn’t require secret management.</em></blockquote><h3>🚀 4. Generate Documentation via Terminal</h3><h4>✅ For Single Module:</h4><pre>./gradlew dokkaJavadoc</pre><p>Generates documentation in Javadoc-style format.</p><h4>✅ For Multi-Module:</h4><pre>./gradlew dokkaHtmlMultiModule</pre><p>Generates HTML documentation across multiple modules — useful for large projects.</p><h3>💡 Output Formats Supported by Dokka</h3><ul><li>dokkaHtml – Default HTML documentation</li><li>dokkaJavadoc – Javadoc-style documentation</li><li>dokkaGfm – GitHub Flavored Markdown (GFM)</li><li>dokkaJekyll – Markdown for Jekyll-based static sites</li></ul><h3>🔍 KDoc vs Javadoc</h3><p>Feature KDoc (Kotlin) Javadoc (Java) Syntax Style Uses /** */ and @param, @return, etc. Same Tool Support Supported via Dokka Native Javadoc Formatting Supports Markdown Plain Text / HTML Rich Output Yes (via Dokka plugins) Yes</p><h3>🛠️ Best Practices for Writing KDoc</h3><ul><li>Use @param, @return, @throws, @see, and @sample properly</li><li>Write concise and actionable sentences</li><li>Don’t repeat method names in descriptions</li><li>Link to related classes/functions when needed</li></ul><pre>/**<br> * Calculates the total price after tax.<br> *<br> * @param price Base price of the item.<br> * @param taxPercent Tax percentage to apply.<br> * @return Final price including tax.<br> */<br>fun calculateTax(price: Double, taxPercent: Double): Double</pre><h3>📚 Final Thoughts</h3><p>Dokka is more than just a documentation generator — it’s an essential part of your <strong>Kotlin developer toolkit</strong>. Whether you’re building open-source libraries or large-scale Android apps, clear documentation helps reduce bugs, increases collaboration, and builds confidence among your team and users.</p><p>So, if you’re still writing Kotlin without Dokka… It’s time to upgrade.</p><h3>📦 Official Docs</h3><p>👉 <a href="https://kotlinlang.org/docs/dokka-introduction.html">https://kotlinlang.org/docs/dokka-introduction.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=154ceb7e6da2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protect your API KEY in android]]></title>
            <link>https://medium.com/@shahricha723/protect-your-api-key-in-android-534a62caf7a4?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/534a62caf7a4</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 10:29:53 GMT</pubDate>
            <atom:updated>2025-07-30T10:29:53.870Z</atom:updated>
            <content:encoded><![CDATA[<h3>Add below in project level build.gradle file</h3><p>classpath ‘com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1’</p><ol><li>Add below in app level build.gradle file</li></ol><p>apply plugin: ‘com.google.android.libraries.mapsplatform.secrets-gradle-plugin’</p><p>3.Create one app.properties file with your API keys which needs to be secured.</p><p>4.And add below in app level build.gradle android {} block.</p><p>secrets {</p><p>defaultPropertiesFileName = ‘app.properties’</p><p>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTKLLxOrOzvSQIuP" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AzoW73VZ_QvvnhQ_" /></figure><p>5. USE API KEY IN YOUR MANIFEST AS BELOW :-</p><p>&lt;meta-data</p><p>android:name=”com.google.android.geo.API_KEY”</p><p>android:value=”${MAPS_API_KEY}” /&gt; <em>&lt;! — Required . Enable it you can get statistics data with channel →</em></p><p>And If you required to Use it In .Kt files then you can fetch using BuildConfig.MAPS_API_KEY</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=534a62caf7a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Spotify into Your Flutter Music App Using spotify_sdk]]></title>
            <link>https://medium.com/@shahricha723/integrating-spotify-into-your-flutter-music-app-using-spotify-sdk-b71ad54685a9?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71ad54685a9</guid>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 10:27:58 GMT</pubDate>
            <atom:updated>2025-07-12T06:13:36.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrating Spotify Service into Your Flutter Music App</h3><p>Integrating Spotify playback into a Flutter music app opens up a world of features — like streaming real tracks, managing player state, and controlling playback — using Spotify’s official SDK. This guide walks you through the <strong>technical setup</strong>, <strong>best practices</strong>, error handling, and <strong>platform limitations</strong> based on real-world experience building a Flutter music app with spotify_sdk.</p><h3>✨ Why spotify_sdk?</h3><p><a href="https://pub.dev/packages/spotify_sdk">spotify_sdk</a> is a Flutter plugin that acts as a wrapper over Spotify&#39;s native SDKs (Android &amp; iOS), allowing control of Spotify playback in authenticated sessions.</p><p>Key features:</p><ul><li>Control playback (play, pause, skip, resume)</li><li>Subscribe to player state</li><li>Launch Spotify client and connect</li><li>Requires <strong>Spotify Premium</strong> for playback (more on this below)</li></ul><h3>🚀 Prerequisites</h3><ul><li>A <strong>Spotify Premium account</strong> (required for playback)</li><li>Spotify App installed on the device</li><li>Flutter 3.x+ setup</li><li>Your app registered in the <a href="https://developer.spotify.com/dashboard/applications">Spotify Developer Dashboard</a></li><li>Android/iOS native setup for Spotify SDK</li></ul><blockquote><em>🔒 Playback using Spotify SDKs (native or via </em><em>spotify_sdk) </em><strong><em>requires Premium</em></strong><em>. Free accounts can access metadata only.</em></blockquote><h3>🔧 Step-by-Step Integration</h3><h3>1. Add Dependencies</h3><pre>dependencies:<br>  spotify_sdk: ^2.3.0<br>  permission_handler: ^11.0.1</pre><h3>2. Register Your App in Spotify Developer Console</h3><ul><li>Go to <a href="https://developer.spotify.com/dashboard">Spotify Developer Dashboard</a></li><li>Create a new app</li><li>Note your <strong>Client ID</strong> and set the following redirect URI:</li><li>Example: yourapp://spotify-login-callback</li></ul><h3>3. Platform-Specific Setup</h3><h4>Android</h4><ul><li>Add to AndroidManifest.xml:</li></ul><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;<br>&lt;application&gt;<br>    &lt;activity&gt;<br>        &lt;intent-filter&gt;<br>            &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>            &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>            &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>            &lt;data android:scheme=&quot;yourapp&quot; android:host=&quot;spotify-login-callback&quot;/&gt;<br>        &lt;/intent-filter&gt;<br>    &lt;/activity&gt;<br>&lt;/application&gt;</pre><ul><li>Set the package name and SHA-1 in the Spotify developer portal.</li></ul><h4>iOS</h4><ul><li>Add to Info.plist:</li></ul><pre>&lt;key&gt;LSApplicationQueriesSchemes&lt;/key&gt;<br>&lt;array&gt;<br>  &lt;string&gt;spotify&lt;/string&gt;<br>&lt;/array&gt;<br>&lt;key&gt;CFBundleURLTypes&lt;/key&gt;<br>&lt;array&gt;<br>  &lt;dict&gt;<br>    &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;<br>    &lt;array&gt;<br>      &lt;string&gt;yourapp&lt;/string&gt;<br>    &lt;/array&gt;<br>  &lt;/dict&gt;<br>&lt;/array&gt;</pre><ul><li>In AppDelegate.swift, handle Spotify token callback manually</li></ul><pre>override func application(<br>  _ application: UIApplication,<br>  open url: URL,<br>  options: [UIApplication.OpenURLOptionsKey : Any] = [:]<br>) -&gt; Bool {<br>  if let fragment = url.fragment {<br>    let components = fragment.components(separatedBy: &quot;&amp;&quot;)<br>    var token = &quot;&quot;<br>    for item in components {<br>      if item.starts(with: &quot;access_token=&quot;) {<br>        token = item.replacingOccurrences(of: &quot;access_token=&quot;, with: &quot;&quot;)<br>        break<br>      }<br>    }<br>    if !token.isEmpty, let controller = window?.rootViewController as? FlutterViewController {<br>      let tokenChannel = FlutterMethodChannel(<br>        name: &quot;spotify_token_channel&quot;,<br>        binaryMessenger: controller.binaryMessenger<br>      )<br>      tokenChannel.invokeMethod(&quot;onAccessTokenReceived&quot;, arguments: token)<br>    }<br>  }<br>  return true<br>}</pre><p>In Flutter For iOS, we are not getting a callback from the Spotify SDK for getAccessToken. I have managed that by communication with iOS(e.g., on resume):</p><pre>@override<br>Future&lt;void&gt; onPageResumed() async {<br>  if (GetPlatform.isIOS) {<br>    await fetchSpotifyTokenAndRedirect();<br>  }<br>}</pre><pre>Future&lt;void&gt; fetchSpotifyTokenAndRedirect() async {<br>  final String token = SharedPref.getString(&#39;pending_spotify_token&#39;);<br>  if (token.isNotEmpty) {<br>    SharedPref.setValue(&quot;spotifyAccessToken&quot;, token);<br>  }</pre><pre>  const MethodChannel tokenChannel = MethodChannel(&quot;spotify_token_channel&quot;);<br>  tokenChannel.setMethodCallHandler((MethodCall call) async {<br>    if (call.method == &quot;onAccessTokenReceived&quot;) {<br>      final String token = call.arguments as String;<br>      SharedPref.setValue(&quot;spotifyAccessToken&quot;, token);<br>    }<br>  });</pre><pre>  final String? bufferedToken = await tokenChannel.invokeMethod&lt;String&gt;(&#39;requestBufferedToken&#39;);<br>  if ((bufferedToken?.isNotEmpty ?? false) == true) {<br>    SharedPref.setValue(&quot;spotifyAccessToken&quot;, bufferedToken!);<br>    await toNamed(AppPages.spotifyHome);<br>  }<br>}</pre><blockquote><em>ℹ️ iOS requires manual handling of the token via custom URL scheme parsing.</em></blockquote><p>For iOS, you have to pass the token in the connectToSpotifyRemote method to make it work smoothly and authenticate the user again.</p><h3>4. Connect to Spotify</h3><pre>bool result = await SpotifySdk.connectToSpotifyRemote(<br>  clientId: &#39;YOUR_CLIENT_ID&#39;,<br>  redirectUrl: &#39;yourapp://spotify-login-callback&#39;,<br>);</pre><blockquote><em>❗️Make sure Spotify is installed and logged in before calling connect.</em></blockquote><h3>🔄 Connection Flowcharts &amp; Decision Points</h3><h3>🎯 Spotify Connection Flow (Error-safe)</h3><pre>  Start([Start App]) --&gt; CheckInstall{Spotify App Installed?}<br>  CheckInstall -- No --&gt; PromptInstall[Prompt to install Spotify App]<br>  CheckInstall -- Yes --&gt; ConnectAttempt[Attempt SDK Connection]<br>  ConnectAttempt --&gt; AuthCheck{User Logged In?}<br>  AuthCheck -- No --&gt; RedirectLogin[Redirect to Spotify Login]<br>  AuthCheck -- Yes --&gt; PremiumCheck{User is Premium?}<br>  PremiumCheck -- No --&gt; ShowUpgradePrompt[Show Premium Required Message]<br>  PremiumCheck -- Yes --&gt; Ready[Playback Ready]</pre><h3>🔁 Managing Player State &amp; Playback</h3><h3>Subscribe to Player State</h3><pre>SpotifySdk.subscribePlayerState().listen((playerState) {<br>  final isPaused = playerState?.isPaused ?? true;<br>  final track = playerState?.track;<br>  final position = playerState?.playbackPosition ?? 0;</pre><pre>  // Buffering logic<br>  bool isBuffering = position == 0 &amp;&amp; !isPaused;<br>});</pre><h3>Play a Track or Context</h3><pre>await SpotifySdk.play(spotifyUri: &#39;spotify:track:YOUR_TRACK_ID&#39;);</pre><h3>⏳ Buffering &amp; Loading Detection</h3><p>Since spotify_sdk doesn’t expose a direct buffering state, we have to manually keep the state updated as per our requirement.</p><pre>bool isLoading = false;</pre><pre>void switchTrack(String uri) async {<br>  isLoading = true;<br>  updateUI();<br>  await SpotifySdk.play(spotifyUri: uri);<br>}</pre><pre>SpotifySdk.subscribePlayerState().listen((playerState) {<br>  if (playerState?.playbackPosition == 0 &amp;&amp; !(playerState?.isPaused ?? true)) {<br>    isLoading = true;<br>  } else {<br>    isLoading = false;<br>  }<br>});</pre><h3>🛠 Common Errors &amp; Handling</h3><h3>1. Connection Failed</h3><pre>try {<br>  await SpotifySdk.connectToSpotifyRemote(...);<br>} catch (e) {<br>  // Retry or show error<br>}</pre><ul><li>Make sure the Spotify app is running.</li><li>Ensure clientId and redirectUri are valid.</li></ul><h3>2. Premium Required (403)</h3><ul><li>Ensure the logged-in user has <strong>Spotify Premium</strong>.</li><li>Validate using Spotify Web API or show UI warning.</li></ul><h3>3. App not installed</h3><ul><li>spotify_sdk throws an exception.</li><li>Use canLaunchUrl() or SpotifySdk.getAppRemoteConnected() to check.</li></ul><h3>4. Not playing after play()</h3><ul><li>Track might be unavailable in region.</li><li>Check playerState?.track == null</li><li>Spotify might delay playing until the app is in the foreground.</li></ul><h3>⚖️ Platform Differences &amp; Limitations</h3><p><em>Note: The SDK </em><strong><em>controls the Spotify app</em></strong><em>, not plays within your Flutter app.</em></p><ul><li>🔹 Android: SpotifyAppRemote</li><li>🔸 iOS: SpotifyAppRemote</li><li><strong>Requires the Spotify App</strong></li><li>✅ Android: Yes</li><li>✅ iOS: Yes</li><li><strong>Playback Control</strong></li><li>✅ Android: Yes</li><li>✅ iOS: Yes</li><li><strong>Background Playback Sync</strong></li><li>⚠️ Android: Works via app switching</li><li>⚠️ iOS: Requires app wake/resume</li><li><strong>Deep Linking to Spotify</strong></li><li>✅ Android: Supported</li><li>✅ iOS: Supported</li><li><strong>Buffer Events</strong></li><li>❌ Android: No native signal (heuristic only)</li><li>❌ iOS: No native signal (heuristic only)</li><li><strong>Token Callback</strong></li><li>✅ Android: Automatic via redirect URI</li><li>⚠️ iOS: Manual via AppDelegate + MethodChannel</li><li><strong>SDK Connection Robustness</strong></li><li>✅ Android: Stable</li><li>⚠️ iOS: Requires manual token buffering</li></ul><blockquote><em>⚠️ On iOS, unlike Android, you must manually handle the token returned via the custom URL scheme, capture it in </em><em>AppDelegate.swift, and pass it to Flutter using a </em><em>MethodChannel. Be sure to listen and persist the token correctly on the Flutter side for a seamless experience.</em></blockquote><blockquote><em>✅ Spotify must be installed on the device and the user must be logged in. </em><em>spotify_sdk only controls the Spotify client, it does not stream music within your Flutter app directly.</em></blockquote><h3>✅ My Approach to Manage Session Expiry</h3><p>To manage this in a Flutter app using spotify_sdk, I implemented the following logic:</p><p><strong>Token Storage</strong></p><ul><li>Store the access token’s expiry time on successful login.</li><li>Persist token and expiry time securely in local storage.</li></ul><p><strong>Periodic Expiry Check</strong></p><ul><li>Before making sensitive calls like connectToSpotifyRemote() or play(), check if the token is about to expire.</li><li>If it’s expired or close to expiry, trigger a fresh call to connectToSpotifyRemote() to refresh the session.</li></ul><p><strong>Auto Re-authentication Logic</strong></p><ul><li>On app resume or on error, verify if the token is valid.</li><li>If it’s expired or revoked, calling connectToSpotifyRemote() again will internally refresh the token if the Spotify app is still authorized.</li></ul><p><strong>Buffered Token Handling (iOS)</strong></p><ul><li>Since iOS requires manual redirect handling, I buffer any new token received and apply it when Flutter resumes.</li></ul><pre>bool isTokenExpired(String expiryTime) {<br>  final expiry = DateTime.tryParse(expiryTime);<br>  return expiry == null || DateTime.now().isAfter(expiry);<br>}</pre><p>📌 Tip: Make sure Spotify app is still installed and the user has not logged out from it. Reconnection will silently fail if the app is removed or inactive.</p><p>This approach ensures the app remains connected and functional even after backgrounding, sleeping, or long idle sessions.</p><p>🎧 How Player State Works in spotify_sdk</p><p>The spotify_sdk plugin allows you to subscribe to the current player state using:</p><pre>SpotifySdk.subscribePlayerState().listen((playerState) {<br>  // handle track, playbackPosition, isPaused<br>});</pre><p>However, this stream is <strong>not persistent</strong> across app lifecycle changes (like background, resume, or app kill). Therefore:</p><ul><li>You should <strong>manually fetch or re-subscribe</strong> to player state during these scenarios:</li><li>When the app resumes from background</li><li>When a new track is played manually</li><li>At intervals (e.g., polling every few seconds if needed)</li></ul><p>Example:</p><pre>Future&lt;void&gt; fetchAndSyncPlayerState() async {<br>  final playerState = await SpotifySdk.getPlayerState();<br>  // update local UI or controller<br>}</pre><h3>🔄 Lifecycle Considerations</h3><h4>Android:</h4><ul><li>If the Spotify app is removed from background/recent apps:</li><li>The SDK may disconnect silently.</li><li>You’ll need to <strong>reconnect</strong> via connectToSpotifyRemote() before calling getPlayerState().</li></ul><h4>iOS:</h4><ul><li>If Spotify is backgrounded or killed:</li><li>SDK loses control.</li><li>Calls to getPlayerState() may fail or return null.</li><li>You must <strong>ensure Spotify is open again</strong> before attempting playback control.</li></ul><p>📌 <strong>Pro Tip</strong>: Use AppLifecycleState to trigger state sync or reconnect Spotify SDK gracefully.</p><pre>@override<br>void didChangeAppLifecycleState(AppLifecycleState state) {<br>  if (state == AppLifecycleState.resumed) {<br>    fetchAndSyncPlayerState();<br>  }<br>}</pre><h3>📦 Optional: Custom Error Mapping</h3><pre>enum SpotifyErrorType {<br>  connectionFailed,<br>  notInstalled,<br>  authError,<br>  unknown,<br>}</pre><pre>SpotifyErrorType mapError(String? message) {<br>  if (message?.contains(&quot;Failed to connect&quot;) == true) return SpotifyErrorType.connectionFailed;<br>  if (message?.contains(&quot;not installed&quot;) == true) return SpotifyErrorType.notInstalled;<br>  if (message?.contains(&quot;auth&quot;) == true) return SpotifyErrorType.authError;<br>  return SpotifyErrorType.unknown;<br>}</pre><h3>🌐 Useful Links</h3><ul><li><a href="https://pub.dev/packages/spotify_sdk">spotify_sdk on pub.dev</a></li><li><a href="https://developer.spotify.com/documentation/android/">Spotify Developer Docs</a></li><li><a href="https://developer.spotify.com/documentation/web-api/reference/#/operations/get-track">Web API URI Reference</a></li><li><a href="https://developer.spotify.com/documentation/ios/">Spotify iOS SDK</a></li><li><a href="https://github.com/spotify/android-sdk">SpotifyAppRemote GitHub</a></li></ul><p>Make sure to:</p><h3>🔐 Respecting Spotify OAuth Scopes</h3><p>When working with Spotify’s Web API or SDKs, <strong>only request and use data based on the scopes explicitly granted</strong> by the user.</p><p>Each OAuth access token is permission-bound, so if your app only requests basic playback scopes (like app-remote-control, user-modify-playback-state.You must not attempt to access profile or playlist data unless additional scopes (e.g., user-read-email, playlist-read-private) were granted.</p><p>This helps you:</p><ul><li>Avoid runtime errors from unauthorized API calls</li><li>Stay compliant with Spotify platform policies</li><li>Improve user trust by not over-requesting access</li></ul><p>📌 <strong>Tip</strong>: After login, inspect the granted scopes if available and get features/UI accordingly to avoid failures.</p><h3>🚀 Final Thoughts</h3><p>If you’re building a modern music app with Flutter, integrating Spotify via spotify_sdk gives you direct control over Spotify playback through native SDKs. While some platform limitations exist, the experience is stable and user-friendly if handled well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71ad54685a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Integrate Google Assistant with Your Flutter Music App]]></title>
            <link>https://medium.com/@shahricha723/integrate-google-assistant-with-your-flutter-music-app-android-only-debe4ba53e65?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/debe4ba53e65</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google-assistant]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 14:35:07 GMT</pubDate>
            <atom:updated>2025-04-19T14:53:24.082Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building a <strong>music player app</strong> in Flutter and want to allow users to say:</p><blockquote>“Hey Google, play Shape of You on SampleApp”</blockquote><p>…then <strong>App Actions</strong> are your secret weapon! Here’s a complete step-by-step guide to integrating Google Assistant support in your Flutter Android app using <strong>deep linking</strong>, <strong>intent filters</strong>, and <strong>Voice Search</strong> support.</p><h3>🚀 What We’ll Build</h3><ul><li>Support for voice commands like “Play <em>[song]</em> on SampleApp”</li><li>Handle intent in Flutter to play the right song</li><li>Upload to beta for testing via <strong>Actions Console</strong></li></ul><h3>🧩 Step 1: Add Deep Linking Support</h3><p>In your AndroidManifest.xml, inside the &lt;activity&gt; tag (usually your MainActivity):</p><pre>&lt;!-- HTTPS and HTTP deep linking --&gt;<br>&lt;intent-filter android:autoVerify=&quot;true&quot;&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>    &lt;data android:scheme=&quot;https&quot; android:host=&quot;www.sampleapp.com&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><pre>&lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>    &lt;data android:scheme=&quot;http&quot; android:host=&quot;www.sampleapp.com&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><h3>🎧 Step 2: Handle Media Search Intents</h3><p>Add these filters to also respond to <strong>media search</strong> commands:</p><pre>&lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.intent.action.MEDIA_SEARCH&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><pre>&lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.media.action.MEDIA_PLAY_FROM_SEARCH&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><h3>🧠 Step 3: Handle Voice Input in Flutter</h3><p>In your Flutter-side service or handler (usually where you control your audio playback):</p><pre>@override<br>Future&lt;void&gt; playFromSearch(String query, [Map&lt;String, dynamic&gt;? extras]) async {<br>  AudioPlayerController.instance().playSongFromGoogleAction(query);<br>}</pre><p>Your method should resolve the song name from query and play it using your audio logic.</p><h3>⚙️ Step 4: Add actions.xml</h3><p>Inside res/xml/actions.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;actions&gt;<br>    &lt;action<br>        intentName=&quot;com.sample.app.PLAY_SONG&quot;<br>        queryPatterns=&quot;@array/ExampleQueries1&quot;&gt;<br>        <br>        &lt;fulfillment<br>            fulfillmentMode=&quot;actions.fulfillment.DEEPLINK&quot;<br>            urlTemplate=&quot;sampleapp://song{?song_name}&quot;&gt;<br>            <br>            &lt;parameter-mapping<br>                intentParameter=&quot;song_name&quot;<br>                urlParameter=&quot;song_name&quot; /&gt;<br>        &lt;/fulfillment&gt;</pre><pre>        &lt;parameter<br>            name=&quot;song_name&quot;<br>            type=&quot;https://schema.org/Text&quot; /&gt;<br>    &lt;/action&gt;<br>&lt;/actions&gt;</pre><h3>🔎 Step 5: Add shortcuts.xml</h3><p>Inside res/xml/shortcuts.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shortcuts xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>           xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;</pre><pre>    &lt;shortcut<br>        android:shortcutId=&quot;play_song&quot;<br>        android:shortcutShortLabel=&quot;@string/shortcut_short_label&quot;<br>        android:shortcutLongLabel=&quot;@string/shortcut_long_label&quot;&gt;<br>        <br>        &lt;capability-binding android:key=&quot;com.sample.app.actions.intent.SEARCH_MUSIC_CONTENT&quot;&gt;<br>            &lt;parameter-binding<br>                android:key=&quot;song&quot;<br>                android:value=&quot;@array/playSongSynonyms&quot; /&gt;<br>        &lt;/capability-binding&gt;<br>    &lt;/shortcut&gt;</pre><pre>    &lt;capability<br>        android:name=&quot;com.sample.app.actions.intent.SEARCH_MUSIC_CONTENT&quot;<br>        app:queryPatterns=&quot;@array/ExampleQueries1&quot;&gt;</pre><pre>        &lt;intent<br>            android:action=&quot;android.intent.action.VIEW&quot;<br>            android:targetClass=&quot;com.sample.app.MainActivity&quot;<br>            android:targetPackage=&quot;com.sample.app&quot;&gt;</pre><pre>            &lt;parameter<br>                android:name=&quot;song&quot;<br>                android:key=&quot;song_name&quot; /&gt;<br>        &lt;/intent&gt;<br>    &lt;/capability&gt;<br>&lt;/shortcuts&gt;</pre><h3>📚 Step 6: Define Strings &amp; Patterns</h3><p>Inside res/values/strings.xml:</p><pre>&lt;string name=&quot;shortcut_long_label&quot;&gt;SampleApp&lt;/string&gt;<br>&lt;string name=&quot;shortcut_short_label&quot;&gt;SampleApp&lt;/string&gt;</pre><pre>&lt;string-array name=&quot;ExampleQueries1&quot;&gt;<br>    &lt;item&gt;Start $song_name music&lt;/item&gt;<br>    &lt;item&gt;Play $song_name music&lt;/item&gt;<br>    &lt;item&gt;play {song_name} in SampleApp&lt;/item&gt;<br>    &lt;item&gt;start {song_name} in SampleApp&lt;/item&gt;<br>    &lt;item&gt;listen to {song_name} in SampleApp&lt;/item&gt;<br>    &lt;item&gt;song&lt;/item&gt;<br>    &lt;item&gt;track&lt;/item&gt;<br>    &lt;item&gt;music&lt;/item&gt;<br>&lt;/string-array&gt;</pre><pre>&lt;string-array name=&quot;playSongQueries&quot;&gt;<br>    &lt;item&gt;play {song_name} in SampleApp&lt;/item&gt;<br>    &lt;item&gt;start {song_name} in SampleApp&lt;/item&gt;<br>    &lt;item&gt;listen to {song_name} in SampleApp&lt;/item&gt;<br>&lt;/string-array&gt;</pre><pre>&lt;string-array name=&quot;playSongSynonyms&quot;&gt;<br>    &lt;item&gt;song&lt;/item&gt;<br>    &lt;item&gt;track&lt;/item&gt;<br>    &lt;item&gt;music&lt;/item&gt;<br>&lt;/string-array&gt;</pre><pre>&lt;string-array name=&quot;searchSongQueries&quot;&gt;<br>    &lt;item&gt;search {song_name} in SampleApp&lt;/item&gt;<br>    &lt;item&gt;find {song_name} in SampleApp&lt;/item&gt;<br>&lt;/string-array&gt;</pre><pre>&lt;string-array name=&quot;searchSongSynonyms&quot;&gt;<br>    &lt;item&gt;song&lt;/item&gt;<br>    &lt;item&gt;track&lt;/item&gt;<br>&lt;/string-array&gt;</pre><h3>☁️ Step 7: Register on <a href="https://console.actions.google.com/">Actions Console</a></h3><ol><li>Sign in to the <a href="https://console.actions.google.com/">Actions Console</a></li><li>Create a <strong>new project</strong></li><li>Choose <strong>“App Actions.”</strong></li><li>Add your <strong>package name</strong></li><li>Upload your <strong>signed APK</strong> (must be in Beta/Internal track on Play Store)</li><li>Add <strong>app actions</strong> like:</li></ol><ul><li>Play {song} on SampleApp</li></ul><h3>🧪 Step 8: Testing</h3><p>Use the <strong>Beta testing from android play console and </strong>directly say:</p><blockquote>“Hey Google, play Shape of You on SampleApp”</blockquote><p>And it should trigger your Flutter playback logic.</p><h3>✅ Final Notes</h3><ul><li>This works only on Android (iOS doesn’t support App Actions)</li><li>Make sure your app is published at least to <strong>internal testing</strong></li><li>You can expand with other BII (Built-in Intents) like pause, resume, etc.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debe4ba53e65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Speech Recognition in Flutter with Audio Session Handling: Mic + Playback Harmony]]></title>
            <link>https://medium.com/@shahricha723/%EF%B8%8F-speech-recognition-in-flutter-with-audio-session-handling-mic-playback-harmony-838dca0ec00b?source=rss-92c9054cfbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/838dca0ec00b</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Richa Shah]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 14:01:27 GMT</pubDate>
            <atom:updated>2025-04-19T14:01:27.003Z</atom:updated>
            <content:encoded><![CDATA[<p>Voice-enabled apps are no longer a novelty — they’re becoming a necessity. Whether it’s for search, command, or dictation, integrating voice recognition is crucial to delivering modern UX.</p><p>But handling <strong>speech input</strong> <em>while also managing audio playback</em> can get tricky, especially on iOS where audio sessions must be carefully configured to avoid interruptions and ensure synchronization.</p><p>In this post, I’ll walk you through implementing <strong>speech recognition with proper audio session configuration</strong>, using the Flutter packages speech_to_text and audio_session. Plus, we’ll handle permissions, playback conflicts, and user feedback dialogs.</p><h3>🧰 Packages Used</h3><p>PackagePurpose<a href="https://pub.dev/packages/speech_to_text">speech_to_text</a>Speech recognition functionalityaudio_sessionAudio session configuration and focus handlingpermission_handlerFor requesting microphone and speech permissions</p><h3>🧠 The Problem</h3><p>When combining <strong>speech recognition</strong> and <strong>music playback or recording</strong> — in the <em>same app</em> or across <em>different apps</em> — you’ll run into session conflicts or microphone unavailability.</p><p>To resolve this, we need to:</p><ul><li>Properly configure the audio session.</li><li>Request and validate permissions.</li><li>Handle speech lifecycle, errors, and status.</li><li>Manage user UI feedback through dialogs.</li></ul><h3>✅ Audio Session Configuration</h3><p>Before we initialize speech recognition, we must configure the session so that both recording (speech) and playback (music/audio) can coexist.</p><pre>Future&lt;void&gt; configureAudioSession() async {<br>  final session = await AudioSession.instance;<br>  await session.configure(AudioSessionConfiguration(<br>    avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,<br>    avAudioSessionCategoryOptions: AVAudioSessionCategoryOptions.allowBluetooth |<br>        AVAudioSessionCategoryOptions.defaultToSpeaker,<br>    avAudioSessionMode: AVAudioSessionMode.measurement,<br>    avAudioSessionRouteSharingPolicy: AVAudioSessionRouteSharingPolicy.defaultPolicy,<br>    androidAudioAttributes: const AndroidAudioAttributes(<br>      contentType: AndroidAudioContentType.speech,<br>      usage: AndroidAudioUsage.voiceCommunication,<br>    ),<br>    androidAudioFocusGainType: AndroidAudioFocusGainType.gain,<br>    androidWillPauseWhenDucked: false,<br>  ));<br>}</pre><p>This ensures:</p><ul><li>Mic support.</li><li>Playback through speaker.</li><li>Low-latency measurement mode (great for speech).</li><li>Non-interruptive Android audio focus.</li></ul><h3>🎤 SpeechToTextMixin: A Reusable Mixin for Speech Recognition</h3><p>To make things clean and testable, I wrapped the logic inside a Mixin so it can be reused across widgets or controllers.</p><h3>💡 Features of the Mixin:</h3><ul><li>Initializes and configures audio session.</li><li>Checks microphone &amp; speech permissions.</li><li>Handles lifecycle of speech recognition.</li><li>Callback hooks for results, status, and errors.</li><li>Integrates with GetX dialogs for UI.</li></ul><h3>📋 Permission Check</h3><p>Request both <strong>microphone</strong> and <strong>speech recognition</strong> permissions before initializing the speech recognize</p><pre>Future&lt;bool&gt; checkMicrophonePermission() async {<br>  bool mic = await getPermission(permission: Permission.microphone);<br>  bool speech = await getPermission(permission: Permission.speech);</pre><pre>  if (!mic || !speech) {<br>    _showMicrophonePermissionRequiredDialog();<br>  }</pre><pre>  return mic &amp;&amp; speech;<br>}</pre><p>Use a custom alert dialog to navigate users to <strong>app settings</strong> if permission is denied.</p><h3>🔄 Toggling Speech Recognition</h3><p>Based on user interaction (like tapping a mic button), we toggle between startListening() and stopListening():</p><pre>Future&lt;void&gt; toggleSpeech({required bool isSpeechEnabled}) async {<br>  if (!isSpeechInitialized) await initSpeechRecognition();</pre><pre>  speechToText.statusListener = updateStatusCallback;</pre><pre>  if (isSpeechEnabled) {<br>    _stopListening();<br>  } else {<br>    if (isSpeechInitialized) _startListening();<br>  }<br>}</pre><h3>🧪 Starting &amp; Stopping Listening</h3><p>We initiate the listen() method with configurations to avoid premature stop due to silence (especially on Android):</p><pre>await speechToText.listen(<br>  onResult: (SpeechRecognitionResult result) =&gt; _onSpeechResult(result),<br>  pauseFor: Duration(seconds: 10),<br>  listenFor: Duration(seconds: 10),<br>  localeId: AppConstant.localEn,<br>  listenOptions: SpeechListenOptions(<br>    listenMode: ListenMode.dictation,<br>    cancelOnError: true,<br>    partialResults: false,<br>    enableHapticFeedback: false,<br>  ),<br>);</pre><p>Once speech is detected and recognized, results are collected and passed back via the callback.</p><h3>💬 Result Callback</h3><p>The mixin allows the parent widget/controller to hook into real-time update</p><pre>void _onSpeechResult(SpeechRecognitionResult result) {<br>  _lastWords += result.recognizedWords;<br>  updateResultCallback(_lastWords);<br>}</pre><p>This is especially useful if you’re using Cubit/BLoC to update UI reactively.</p><h3>🧼 Cleanup</h3><p>When speech recognition is no longer needed (like on dispose), stop the session cleanly:</p><pre>Future&lt;void&gt; disposeSpeechRecognition() async {<br>  await speechToText.stop();<br>}</pre><h3>📱 Real UX Touch: Speak Now Dialog</h3><p>Optionally, you can wrap the listening process inside a custom “Speak Now” dialog to guide the user</p><pre>openSpeakNowDialog(context, controller, () async {<br>  await _stopListening();<br>  if (Get.isDialogOpen == true) goBack();<br>});</pre><h3>🧩 Final Thoughts</h3><p>Using this approach, we get:</p><ul><li>Seamless <strong>audio session management</strong>.</li><li>Robust <strong>speech recognition</strong> lifecycle.</li><li><strong>Permission safety</strong> and graceful fallbacks.</li><li>Clean and <strong>reusable mixin logic</strong>.</li><li>User-friendly feedback through dialogs.</li></ul><p>Whether you’re building a <strong>music app with voice search</strong>, a <strong>hands-free assistant</strong>, or a <strong>voice-controlled tool</strong>, this architecture should serve as a strong foundation.</p><h3>💻 Resources &amp; Plugins</h3><ul><li><a href="https://pub.dev/packages/speech_to_text">speech_to_text</a></li><li>audio_session</li><li>permission_handler</li></ul><p>Got questions or want to integrate this into your Flutter app? Drop a comment or connect on <a href="https://github.com/richanshah">https://github.com/richanshah</a>/ <a href="https://www.linkedin.com/in/richa-shah-159870a0/">https://www.linkedin.com/in/richa-shah-159870a0/</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838dca0ec00b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>