<?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 Kartik Tungenwar on Medium]]></title>
        <description><![CDATA[Stories by Kartik Tungenwar on Medium]]></description>
        <link>https://medium.com/@tungenwarkartick?source=rss-9b1784f15bd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ExXHHtiHN8H6MeYX.jpg</url>
            <title>Stories by Kartik Tungenwar on Medium</title>
            <link>https://medium.com/@tungenwarkartick?source=rss-9b1784f15bd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:54:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tungenwarkartick/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[Step-by-Step Guide: Building Biometric Authentication Fingerprint in Compose Multiplatform for…]]></title>
            <link>https://medium.com/@tungenwarkartick/step-by-step-guide-building-biometric-authentication-fingerprint-in-compose-multiplatform-for-c80095bba1d2?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c80095bba1d2</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 09:18:49 GMT</pubDate>
            <atom:updated>2026-10-02T09:23:28.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step-by-Step Guide: Building Biometric Authentication Fingerprint in Compose Multiplatform for Android &amp; iOS</h3><h3><strong>Introduction</strong></h3><p>Learn how to build a unified, secure biometric authentication solution for Android and iOS using Kotlin Multiplatform, Compose Multiplatform, Jetpack Biometric, and Apple’s LocalAuthentication framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGYP53alCi-vtEkgN_Spxw.png" /></figure><p>Securing mobile applications with biometric authentication?such as Fingerprint (Touch ID) and Face Recognition (Face ID)?provides both enhanced security and seamless user experience.</p><p>In Kotlin Multiplatform (KMP) and Compose Multiplatform apps, biometric APIs are platform-native. Android uses Jetpack?s androidx.biometric.BiometricPrompt, while iOS relies on Apple?s LocalAuthentication framework (LAContext).</p><p>In this tutorial, we will step-by-step construct a clean, production-ready Biometric Authenticator using the expect/actual pattern, Compose Multiplatform UI, and MVVM architecture.</p><h3>Key Features We Will Implement</h3><p>1.Hardware &amp; Capability Detection: Determine whether Fingerprint, Face ID, or generic biometrics are available on the device.</p><p>2.Platform-Specific Drivers:</p><ul><li>Android: Jetpack BiometricPrompt + FragmentActivity handling.</li><li>iOS: Objective-C Interop with Apple’s LAContext.</li></ul><p>3.State Management: Reactive UI states using Kotlin StateFlow and Compose LaunchedEffect.</p><p>4.Audit Logging: Session history recording success, error, and cancellation events.</p><h3><strong>Step 1: Define Common Models and Core Abstraction</strong></h3><p>First, define common domain models in commonMain to represent biometric capabilities, statuses, and authentication outcomes.</p><pre>// shared/src/commonMain/kotlin/.../model/BiometricModels.kt<br>package com.biometric.authenticator.model<br><br>enum class BiometricType(val displayName: String) {<br>    FINGERPRINT(&quot;Fingerprint&quot;),<br>    FACE(&quot;Face Recognition&quot;),<br>    BIOMETRIC(&quot;Biometric Authentication&quot;),<br>    NONE(&quot;None Available&quot;)<br>}<br><br>sealed interface BiometricStatus {<br>    data class Available(val type: BiometricType) : BiometricStatus<br>    data class NotAvailable(val reason: String) : BiometricStatus<br>    object NotEnrolled : BiometricStatus<br>    object HardwareUnavailable : BiometricStatus<br>}<br><br>sealed interface BiometricAuthResult {<br>    object Success : BiometricAuthResult<br>    data class Error(val message: String, val errorCode: Int = 0) : BiometricAuthResult<br>    object Failed : BiometricAuthResult<br>    object Canceled : BiometricAuthResult<br>}</pre><p>Next, we specify the contract that every platform must fulfill, along with a Composable expect function to<br>retrieve the current instance:</p><pre>// shared/src/commonMain/kotlin/.../biometric/BiometricAuthenticator.kt<br>package com.biometric.authenticator.biometric<br><br>import androidx.compose.runtime.Composable<br>import com.biometric.authenticator.model.BiometricAuthResult<br>import com.biometric.authenticator.model.BiometricStatus<br>import com.biometric.authenticator.model.BiometricType<br><br>interface BiometricAuthenticator {<br>    fun isBiometricAvailable(): BiometricStatus<br>    fun getBiometricType(): BiometricType<br>    suspend fun authenticate(<br>        title: String = &quot;Biometric Verification&quot;,<br>        subtitle: String = &quot;Confirm your identity&quot;,<br>        description: String = &quot;Please authenticate using your fingerprint or face&quot;,<br>        negativeButtonText: String = &quot;Cancel&quot;<br>    ): BiometricAuthResult<br>}<br><br>@Composable<br>expect fun rememberBiometricAuthenticator(): BiometricAuthenticator<br></pre><h3>Step 2:Android Implementation with BiometricPrompt</h3><p>On Android, displaying a native biometric prompt requires a FragmentActivity context. We check hardware capabilities using AndroidX BiometricManager and wrap the callback-based BiometricPrompt in suspendCancellableCoroutine.</p><pre>// shared/src/androidMain/kotlin/.../rememberBiometricAuthenticator.android.kt<br>import android.content.Context<br>import android.content.ContextWrapper<br>import android.content.pm.PackageManager<br>import android.os.Build<br>import androidx.biometric.BiometricManager<br>import androidx.biometric.BiometricPrompt<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.remember<br>import androidx.compose.ui.platform.LocalContext<br>import androidx.core.content.ContextCompat<br>import androidx.fragment.app.FragmentActivity<br>import com.biometric.authenticator.model.BiometricAuthResult<br>import com.biometric.authenticator.model.BiometricStatus<br>import com.biometric.authenticator.model.BiometricType<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.suspendCancellableCoroutine<br>import kotlinx.coroutines.withContext<br>import kotlin.coroutines.resume<br><br>class AndroidBiometricAuthenticator(<br>    private val context: Context<br>) : BiometricAuthenticator {<br><br>    private val biometricManager = BiometricManager.from(context)<br><br>    override fun isBiometricAvailable(): BiometricStatus {<br>        val authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG or<br>                BiometricManager.Authenticators.BIOMETRIC_WEAK<br>        return when (biometricManager.canAuthenticate(authenticators)) {<br>            BiometricManager.BIOMETRIC_SUCCESS -&gt; {<br>                BiometricStatus.Available(getBiometricType())<br>            }<br>            BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE,<br>            BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -&gt; BiometricStatus.HardwareUnavailable<br>            BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -&gt; BiometricStatus.NotEnrolled<br>            BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -&gt;<br>                BiometricStatus.NotAvailable(&quot;Security update required&quot;)<br>            BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -&gt;<br>                BiometricStatus.NotAvailable(&quot;Biometrics not supported on this device&quot;)<br>            BiometricManager.BIOMETRIC_STATUS_UNKNOWN -&gt;<br>                BiometricStatus.NotAvailable(&quot;Biometric status unknown&quot;)<br>            else -&gt; BiometricStatus.NotAvailable(&quot;Biometric authentication unavailable&quot;)<br>        }<br>    }<br><br>    override fun getBiometricType(): BiometricType {<br>        val pm = context.packageManager<br>        val hasFingerprint = pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)<br>        val hasFace = if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) {<br>            pm.hasSystemFeature(PackageManager.FEATURE_FACE)<br>        } else false<br><br>        return when {<br>            hasFingerprint &amp;&amp; !hasFace -&gt; BiometricType.FINGERPRINT<br>            hasFace &amp;&amp; !hasFingerprint -&gt; BiometricType.FACE<br>            hasFingerprint &amp;&amp; hasFace -&gt; BiometricType.FINGERPRINT<br>            else -&gt; BiometricType.BIOMETRIC<br>        }<br>    }<br><br>    override suspend fun authenticate(<br>        title: String,<br>        subtitle: String,<br>        description: String,<br>        negativeButtonText: String<br>    ): BiometricAuthResult = withContext(Dispatchers.Main) {<br>        val activity = context.findFragmentActivity()<br>            ?: return@withContext BiometricAuthResult.Error(<br>                &quot;Host Activity must be a FragmentActivity to display BiometricPrompt&quot;<br>            )<br><br>        suspendCancellableCoroutine&lt;BiometricAuthResult&gt; { continuation -&gt;<br>            val executor = ContextCompat.getMainExecutor(activity)<br><br>            val callback = object : BiometricPrompt.AuthenticationCallback() {<br>                override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {<br>                    if (continuation.isActive) {<br>                        continuation.resume(BiometricAuthResult.Success)<br>                    }<br>                }<br><br>                override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {<br>                    if (continuation.isActive) {<br>                        if (errorCode == BiometricPrompt.ERROR_USER_CANCELED ||<br>                            errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON<br>                        ) {<br>                            continuation.resume(BiometricAuthResult.Canceled)<br>                        } else {<br>                            continuation.resume(BiometricAuthResult.Error(errString.toString(), errorCode))<br>                        }<br>                    }<br>                }<br><br>                override fun onAuthenticationFailed() {<br>                    if (continuation.isActive) {<br>                        continuation.resume(BiometricAuthResult.Failed)<br>                    }<br>                }<br>            }<br><br>            val promptInfo = BiometricPrompt.PromptInfo.Builder()<br>                .setTitle(title)<br>                .setSubtitle(subtitle)<br>                .setDescription(description)<br>                .setNegativeButtonText(negativeButtonText)<br>                .setAllowedAuthenticators(<br>                    BiometricManager.Authenticators.BIOMETRIC_STRONG or<br>                            BiometricManager.Authenticators.BIOMETRIC_WEAK<br>                )<br>                .build()<br><br>            val biometricPrompt = BiometricPrompt(activity, executor, callback)<br>            biometricPrompt.authenticate(promptInfo)<br><br>            continuation.invokeOnCancellation {<br>                biometricPrompt.cancelAuthentication()<br>            }<br>        }<br>    }<br><br>    private fun Context.findFragmentActivity(): FragmentActivity? {<br>        var currentContext = this<br>        while (currentContext is ContextWrapper) {<br>            if (currentContext is FragmentActivity) {<br>                return currentContext<br>            }<br>            currentContext = currentContext.baseContext<br>        }<br>        return null<br>    }<br>}</pre><p>To enable biometric authentication on Android, add the following permissions to your AndroidManifest.xml file inside the &lt;manifest&gt; tag:</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br><br>    &lt;!-- Standard Biometric API (Android 9.0 / API level 28 and above) --&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.USE_BIOMETRIC&quot; /&gt;<br><br>    &lt;!-- Legacy Fingerprint API (Android 8.1 / API level 27 and below) --&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.USE_FINGERPRINT&quot; /&gt;<br><br>    &lt;application<br>        ... &gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>Pro Tip: Always ensure your host Android Activity inherits from FragmentActivity or ComponentActivity (with<br>FragmentActivity support) when using AndroidX BiometricPrompt.</p><h3><strong>Step3: IOS Implementation with Apple’s LocalAuthentication</strong></h3><p>On iOS, Kotlin/Native allows us to invoke Apple’s LocalAuthentication framework directly without writing any Swift or Objective-C code! We use LAContext, canEvaluatePolicy with LAPolicyDeviceOwnerAuthenticationWithBiometrics, and handle Objective-C error pointers with memScoped.</p><pre>// shared/src/iosMain/kotlin/.../rememberBiometricAuthenticator.ios.kt<br>package com.biometric.authenticator.biometric<br><br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.remember<br>import com.biometric.authenticator.model.BiometricAuthResult<br>import com.biometric.authenticator.model.BiometricStatus<br>import com.biometric.authenticator.model.BiometricType<br>import kotlinx.cinterop.BetaInteropApi<br>import kotlinx.cinterop.ExperimentalForeignApi<br>import kotlinx.cinterop.ObjCObjectVar<br>import kotlinx.cinterop.alloc<br>import kotlinx.cinterop.memScoped<br>import kotlinx.cinterop.ptr<br>import kotlinx.cinterop.value<br>import kotlinx.coroutines.suspendCancellableCoroutine<br>import platform.Foundation.NSError<br>import platform.LocalAuthentication.LABiometryTypeFaceID<br>import platform.LocalAuthentication.LABiometryTypeNone<br>import platform.LocalAuthentication.LABiometryTypeOpticID<br>import platform.LocalAuthentication.LABiometryTypeTouchID<br>import platform.LocalAuthentication.LAContext<br>import platform.LocalAuthentication.LAErrorBiometryNotAvailable<br>import platform.LocalAuthentication.LAErrorBiometryNotEnrolled<br>import platform.LocalAuthentication.LAErrorUserCancel<br>import platform.LocalAuthentication.LAPolicyDeviceOwnerAuthenticationWithBiometrics<br>import kotlin.coroutines.resume<br><br>class IOSBiometricAuthenticator : BiometricAuthenticator {<br><br>    @OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)<br>    override fun isBiometricAvailable(): BiometricStatus {<br>        val laContext = LAContext()<br>        return memScoped {<br>            val errorPtr = alloc&lt;ObjCObjectVar&lt;NSError?&gt;&gt;()<br>            val canEvaluate = laContext.canEvaluatePolicy(<br>                LAPolicyDeviceOwnerAuthenticationWithBiometrics,<br>                errorPtr.ptr<br>            )<br><br>            if (canEvaluate) {<br>                val type = getBiometricTypeForContext(laContext)<br>                BiometricStatus.Available(type)<br>            } else {<br>                val nsError = errorPtr.value<br>                val errorCode = nsError?.code<br>                when (errorCode) {<br>                    LAErrorBiometryNotEnrolled -&gt; BiometricStatus.NotEnrolled<br>                    LAErrorBiometryNotAvailable -&gt; BiometricStatus.HardwareUnavailable<br>                    else -&gt; {<br>                        val message = nsError?.localizedDescription ?: &quot;Biometric authentication not available&quot;<br>                        BiometricStatus.NotAvailable(message)<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    @OptIn(ExperimentalForeignApi::class)<br>    override fun getBiometricType(): BiometricType {<br>        val laContext = LAContext()<br>        memScoped {<br>            val errorPtr = alloc&lt;ObjCObjectVar&lt;NSError?&gt;&gt;()<br>            laContext.canEvaluatePolicy(<br>                LAPolicyDeviceOwnerAuthenticationWithBiometrics,<br>                errorPtr.ptr<br>            )<br>        }<br>        return getBiometricTypeForContext(laContext)<br>    }<br><br>    private fun getBiometricTypeForContext(laContext: LAContext): BiometricType {<br>        return when (laContext.biometryType) {<br>            LABiometryTypeTouchID -&gt; BiometricType.FINGERPRINT<br>            LABiometryTypeFaceID -&gt; BiometricType.FACE<br>            LABiometryTypeOpticID -&gt; BiometricType.FACE<br>            LABiometryTypeNone -&gt; BiometricType.NONE<br>            else -&gt; BiometricType.BIOMETRIC<br>        }<br>    }<br><br>    override suspend fun authenticate(<br>        title: String,<br>        subtitle: String,<br>        description: String,<br>        negativeButtonText: String<br>    ): BiometricAuthResult = suspendCancellableCoroutine { continuation -&gt;<br>        val laContext = LAContext()<br>        laContext.localizedCancelTitle = negativeButtonText<br><br>        laContext.evaluatePolicy(<br>            LAPolicyDeviceOwnerAuthenticationWithBiometrics,<br>            localizedReason = description<br>        ) { success, nsError -&gt;<br>            if (continuation.isActive) {<br>                if (success) {<br>                    continuation.resume(BiometricAuthResult.Success)<br>                } else if (nsError != null) {<br>                    if (nsError.code == LAErrorUserCancel) {<br>                        continuation.resume(BiometricAuthResult.Canceled)<br>                    } else {<br>                        continuation.resume(<br>                            BiometricAuthResult.Error(<br>                                nsError.localizedDescription,<br>                                nsError.code.toInt()<br>                            )<br>                        )<br>                    }<br>                } else {<br>                    continuation.resume(BiometricAuthResult.Failed)<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>actual fun rememberBiometricAuthenticator(): BiometricAuthenticator {<br>    return remember { IOSBiometricAuthenticator() }<br>}</pre><p>In Xcode, open your Info.plist file (or select your target $\rightarrow$ <strong>Info</strong> tab) and add the keys:</p><ul><li><strong>NSFaceIDUsageDescription</strong> (Privacy - Face ID Usage Description): A clear message explaining why your app needs biometric authentication. <strong>Apple will reject apps with vague descriptions.</strong></li><li><strong>CADisableMinimumFrameDurationOnPhone</strong>: Ensures high-refresh-rate ProMotion displays (120Hz) work smoothly on supported iPhones.</li></ul><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br> &lt;key&gt;CADisableMinimumFrameDurationOnPhone&lt;/key&gt;<br> &lt;true/&gt;<br> &lt;key&gt;NSFaceIDUsageDescription&lt;/key&gt;<br> &lt;string&gt;Biometric authentication is required to secure your data and verify your identity.&lt;/string&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><h3><strong>Step4: State Management with ViewModel &amp; StateFlow</strong></h3><p>The BiometricViewModel coordinates between UI events and the platform authenticator. It updates an immutable BiometricUiState data flow and appends structured audit log entries for every security attempt.</p><pre>// shared/src/commonMain/kotlin/.../viewmodel/BiometricViewModel.kt<br>package com.biometric.authenticator.viewmodel<br><br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.viewModelScope<br>import com.biometric.authenticator.biometric.BiometricAuthenticator<br>import com.biometric.authenticator.model.BiometricAuthResult<br>import com.biometric.authenticator.model.BiometricStatus<br>import com.biometric.authenticator.model.BiometricType<br>import kotlinx.coroutines.flow.MutableStateFlow<br>import kotlinx.coroutines.flow.StateFlow<br>import kotlinx.coroutines.flow.asStateFlow<br>import kotlinx.coroutines.flow.update<br>import kotlinx.coroutines.launch<br><br>sealed interface AuthState {<br>    object Idle : AuthState<br>    object Authenticating : AuthState<br>    data class Success(val message: String) : AuthState<br>    data class Error(val message: String) : AuthState<br>}<br><br>data class AuthLogEntry(<br>    val id: String,<br>    val timeString: String,<br>    val status: String,<br>    val details: String,<br>    val isSuccess: Boolean<br>)<br><br>data class BiometricUiState(<br>    val biometricStatus: BiometricStatus = BiometricStatus.NotAvailable(&quot;Checking...&quot;),<br>    val biometricType: BiometricType = BiometricType.NONE,<br>    val authState: AuthState = AuthState.Idle,<br>    val isAuthenticated: Boolean = false,<br>    val secretVaultData: String? = null,<br>    val authLogs: List&lt;AuthLogEntry&gt; = emptyList()<br>)<br><br>class BiometricViewModel : ViewModel() {<br><br>    private val _uiState = MutableStateFlow(BiometricUiState())<br>    val uiState: StateFlow&lt;BiometricUiState&gt; = _uiState.asStateFlow()<br><br>    private var logCounter = 1<br><br>    fun checkBiometricAvailability(authenticator: BiometricAuthenticator) {<br>        val status = authenticator.isBiometricAvailable()<br>        val type = authenticator.getBiometricType()<br>        _uiState.update {<br>            it.copy(<br>                biometricStatus = status,<br>                biometricType = type<br>            )<br>        }<br>    }<br><br>    fun authenticate(authenticator: BiometricAuthenticator) {<br>        viewModelScope.launch {<br>            _uiState.update { it.copy(authState = AuthState.Authenticating) }<br><br>            val result = authenticator.authenticate(<br>                title = &quot;Biometric Security Check&quot;,<br>                subtitle = &quot;Confirm your identity&quot;,<br>                description = &quot;Touch fingerprint sensor or scan face to unlock vault&quot;,<br>                negativeButtonText = &quot;Cancel&quot;<br>            )<br><br>            val timeString = formatTime(logCounter)<br><br>            when (result) {<br>                is BiometricAuthResult.Success -&gt; {<br>                    val log = AuthLogEntry(<br>                        id = &quot;LOG-#$logCounter&quot;,<br>                        timeString = timeString,<br>                        status = &quot;SUCCESS&quot;,<br>                        details = &quot;Biometric match verified. Vault unlocked.&quot;,<br>                        isSuccess = true<br>                    )<br>                    logCounter++<br>                    _uiState.update {<br>                        it.copy(<br>                            isAuthenticated = true,<br>                            authState = AuthState.Success(&quot;Successfully Authenticated!&quot;),<br>                            secretVaultData = &quot;AES-256 Key: 0x8F9A4B21-CONFIDENTIAL-SESSION-TOKEN&quot;,<br>                            authLogs = listOf(log) + it.authLogs<br>                        )<br>                    }<br>                }<br>                is BiometricAuthResult.Error -&gt; {<br>                    val log = AuthLogEntry(<br>                        id = &quot;LOG-#$logCounter&quot;,<br>                        timeString = timeString,<br>                        status = &quot;ERROR&quot;,<br>                        details = result.message,<br>                        isSuccess = false<br>                    )<br>                    logCounter++<br>                    _uiState.update {<br>                        it.copy(<br>                            authState = AuthState.Error(result.message),<br>                            authLogs = listOf(log) + it.authLogs<br>                        )<br>                    }<br>                }<br>                is BiometricAuthResult.Failed -&gt; {<br>                    val log = AuthLogEntry(<br>                        id = &quot;LOG-#$logCounter&quot;,<br>                        timeString = timeString,<br>                        status = &quot;FAILED&quot;,<br>                        details = &quot;Fingerprint / Face not recognized.&quot;,<br>                        isSuccess = false<br>                    )<br>                    logCounter++<br>                    _uiState.update {<br>                        it.copy(<br>                            authState = AuthState.Error(&quot;Biometric not recognized. Please try again.&quot;),<br>                            authLogs = listOf(log) + it.authLogs<br>                        )<br>                    }<br>                }<br>                is BiometricAuthResult.Canceled -&gt; {<br>                    val log = AuthLogEntry(<br>                        id = &quot;LOG-#$logCounter&quot;,<br>                        timeString = timeString,<br>                        status = &quot;CANCELED&quot;,<br>                        details = &quot;User canceled authentication prompt.&quot;,<br>                        isSuccess = false<br>                    )<br>                    logCounter++<br>                    _uiState.update {<br>                        it.copy(<br>                            authState = AuthState.Idle,<br>                            authLogs = listOf(log) + it.authLogs<br>                        )<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    fun logout() {<br>        _uiState.update {<br>            it.copy(<br>                isAuthenticated = false,<br>                secretVaultData = null,<br>                authState = AuthState.Idle<br>            )<br>        }<br>    }<br><br>    fun clearLogs() {<br>        _uiState.update { it.copy(authLogs = emptyList()) }<br>    }<br><br>    fun dismissError() {<br>        _uiState.update { it.copy(authState = AuthState.Idle) }<br>    }<br><br>    private fun formatTime(attempt: Int): String {<br>        return &quot;Attempt #$attempt&quot;<br>    }<br>}</pre><h3><strong>Step5: Declarative UI in Compose Multiplatform</strong></h3><p>Using Compose Multiplatform, we create an interactive, accessible, and beautifully styled screen(BiometricAuthScreen). It features a custom fingerprint icon drawn directly on a Compose Canvas, status cards<br>with dynamic color highlights, an unlocked secret vault card, and live audit logging.</p><pre>//shared/src/commonMain/kotlin/.../ui/BiometricAuthScreen.kt<br>package com.biometric.authenticator.ui<br><br>import androidx.compose.animation.AnimatedVisibility<br>import androidx.compose.animation.animateColorAsState<br>import androidx.compose.foundation.Canvas<br>import androidx.compose.foundation.background<br>import androidx.compose.foundation.clickable<br>import androidx.compose.foundation.layout.Arrangement<br>import androidx.compose.foundation.layout.Box<br>import androidx.compose.foundation.layout.Column<br>import androidx.compose.foundation.layout.Row<br>import androidx.compose.foundation.layout.Spacer<br>import androidx.compose.foundation.layout.fillMaxSize<br>import androidx.compose.foundation.layout.fillMaxWidth<br>import androidx.compose.foundation.layout.height<br>import androidx.compose.foundation.layout.padding<br>import androidx.compose.foundation.layout.size<br>import androidx.compose.foundation.layout.width<br>import androidx.compose.foundation.lazy.LazyColumn<br>import androidx.compose.foundation.lazy.items<br>import androidx.compose.foundation.shape.CircleShape<br>import androidx.compose.foundation.shape.RoundedCornerShape<br>import androidx.compose.material3.Button<br>import androidx.compose.material3.ButtonDefaults<br>import androidx.compose.material3.Card<br>import androidx.compose.material3.CardDefaults<br>import androidx.compose.material3.CircularProgressIndicator<br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.material3.OutlinedButton<br>import androidx.compose.material3.OutlinedCard<br>import androidx.compose.material3.Scaffold<br>import androidx.compose.material3.Surface<br>import androidx.compose.material3.Text<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.LaunchedEffect<br>import androidx.compose.runtime.collectAsState<br>import androidx.compose.runtime.getValue<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.draw.clip<br>import androidx.compose.ui.graphics.Color<br>import androidx.compose.ui.graphics.drawscope.Stroke<br>import androidx.compose.ui.text.font.FontFamily<br>import androidx.compose.ui.text.font.FontWeight<br>import androidx.compose.ui.text.style.TextAlign<br>import androidx.compose.ui.unit.dp<br>import androidx.compose.ui.unit.sp<br>import androidx.lifecycle.viewmodel.compose.viewModel<br>import com.biometric.authenticator.biometric.rememberBiometricAuthenticator<br>import com.biometric.authenticator.model.BiometricStatus<br>import com.biometric.authenticator.model.BiometricType<br>import com.biometric.authenticator.viewmodel.AuthLogEntry<br>import com.biometric.authenticator.viewmodel.AuthState<br>import com.biometric.authenticator.viewmodel.BiometricUiState<br>import com.biometric.authenticator.viewmodel.BiometricViewModel<br><br>@Composable<br>fun BiometricAuthScreen(<br>    viewModel: BiometricViewModel = viewModel { BiometricViewModel() }<br>) {<br>    val authenticator = rememberBiometricAuthenticator()<br>    val uiState by viewModel.uiState.collectAsState()<br><br>    LaunchedEffect(authenticator) {<br>        viewModel.checkBiometricAvailability(authenticator)<br>    }<br><br>    MaterialTheme {<br>        Scaffold(<br>            modifier = Modifier.fillMaxSize()<br>        ) { paddingValues -&gt;<br>            LazyColumn(<br>                modifier = Modifier<br>                    .fillMaxSize()<br>                    .padding(paddingValues)<br>                    .padding(horizontal = 16.dp, vertical = 12.dp),<br>                verticalArrangement = Arrangement.spacedBy(16.dp)<br>            ) {<br>                // Header<br>                item {<br>                    HeaderCard()<br>                }<br><br>                // Device Capability Status<br>                item {<br>                    DeviceStatusCard(<br>                        status = uiState.biometricStatus,<br>                        type = uiState.biometricType,<br>                        onRefresh = { viewModel.checkBiometricAvailability(authenticator) }<br>                    )<br>                }<br><br>                // Authentication Action Card<br>                item {<br>                    AuthActionCard(<br>                        uiState = uiState,<br>                        onAuthenticate = { viewModel.authenticate(authenticator) },<br>                        onLogout = { viewModel.logout() }<br>                    )<br>                }<br><br>                // Secret Vault Card (when authenticated)<br>                item {<br>                    AnimatedVisibility(visible = uiState.isAuthenticated) {<br>                        SecretVaultCard(<br>                            secretData = uiState.secretVaultData ?: &quot;No data&quot;<br>                        )<br>                    }<br>                }<br><br>                // Audit Log Section<br>                item {<br>                    LogSectionHeader(<br>                        logCount = uiState.authLogs.size,<br>                        onClearLogs = { viewModel.clearLogs() }<br>                    )<br>                }<br><br>                if (uiState.authLogs.isEmpty()) {<br>                    item {<br>                        EmptyLogCard()<br>                    }<br>                } else {<br>                    items(<br>                        items = uiState.authLogs,<br>                        key = { it.id + it.timeString }<br>                    ) { logEntry -&gt;<br>                        LogEntryRow(logEntry)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>private fun HeaderCard() {<br>    Surface(<br>        modifier = Modifier.fillMaxWidth(),<br>        shape = RoundedCornerShape(20.dp),<br>        color = MaterialTheme.colorScheme.primaryContainer,<br>        shadowElevation = 2.dp<br>    ) {<br>        Row(<br>            modifier = Modifier.padding(20.dp),<br>            verticalAlignment = Alignment.CenterVertically<br>        ) {<br>            Box(<br>                modifier = Modifier<br>                    .size(56.dp)<br>                    .clip(CircleShape)<br>                    .background(MaterialTheme.colorScheme.primary),<br>                contentAlignment = Alignment.Center<br>            ) {<br>                FingerprintCanvasIcon(<br>                    modifier = Modifier.size(36.dp),<br>                    color = MaterialTheme.colorScheme.onPrimary<br>                )<br>            }<br>            Spacer(modifier = Modifier.width(16.dp))<br>            Column {<br>                Text(<br>                    text = &quot;Biometric Authenticator&quot;,<br>                    style = MaterialTheme.typography.titleLarge,<br>                    fontWeight = FontWeight.Bold,<br>                    color = MaterialTheme.colorScheme.onPrimaryContainer<br>                )<br>                Text(<br>                    text = &quot;MVVM ? Android &amp; iOS Support&quot;,<br>                    style = MaterialTheme.typography.bodyMedium,<br>                    color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f)<br>                )<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>private fun DeviceStatusCard(<br>    status: BiometricStatus,<br>    type: BiometricType,<br>    onRefresh: () -&gt; Unit<br>) {<br>    Card(<br>        modifier = Modifier.fillMaxWidth(),<br>        shape = RoundedCornerShape(16.dp),<br>        colors = CardDefaults.cardColors(<br>            containerColor = MaterialTheme.colorScheme.surfaceVariant<br>        )<br>    ) {<br>        Column(<br>            modifier = Modifier.padding(16.dp)<br>        ) {<br>            Row(<br>                modifier = Modifier.fillMaxWidth(),<br>                horizontalArrangement = Arrangement.SpaceBetween,<br>                verticalAlignment = Alignment.CenterVertically<br>            ) {<br>                Text(<br>                    text = &quot;Device Biometric Support&quot;,<br>                    style = MaterialTheme.typography.titleMedium,<br>                    fontWeight = FontWeight.SemiBold<br>                )<br>                OutlinedButton(<br>                    onClick = onRefresh,<br>                    shape = RoundedCornerShape(12.dp)<br>                ) {<br>                    Text(&quot;Check&quot;, fontSize = 12.sp)<br>                }<br>            }<br><br>            Spacer(modifier = Modifier.height(12.dp))<br><br>            val (statusText, statusBg, statusContentColor) = when (status) {<br>                is BiometricStatus.Available -&gt; Triple(<br>                    &quot;Ready (${status.type.displayName})&quot;,<br>                    Color(0xFFE8F5E9),<br>                    Color(0xFF2E7D32)<br>                )<br>                is BiometricStatus.NotEnrolled -&gt; Triple(<br>                    &quot;Not Enrolled (No Fingerprint/Face set)&quot;,<br>                    Color(0xFFFFF8E1),<br>                    Color(0xFFF57F17)<br>                )<br>                is BiometricStatus.HardwareUnavailable -&gt; Triple(<br>                    &quot;Hardware Unavailable&quot;,<br>                    Color(0xFFFFEBEE),<br>                    Color(0xFFC62828)<br>                )<br>                is BiometricStatus.NotAvailable -&gt; Triple(<br>                    status.reason,<br>                    Color(0xFFFFEBEE),<br>                    Color(0xFFC62828)<br>                )<br>            }<br><br>            Row(<br>                verticalAlignment = Alignment.CenterVertically<br>            ) {<br>                Text(<br>                    text = &quot;Type: &quot;,<br>                    style = MaterialTheme.typography.bodyMedium,<br>                    fontWeight = FontWeight.Medium<br>                )<br>                Text(<br>                    text = type.displayName,<br>                    style = MaterialTheme.typography.bodyMedium,<br>                    fontWeight = FontWeight.Bold,<br>                    color = MaterialTheme.colorScheme.primary<br>                )<br>            }<br><br>            Spacer(modifier = Modifier.height(8.dp))<br><br>            Surface(<br>                shape = RoundedCornerShape(8.dp),<br>                color = statusBg,<br>                modifier = Modifier.fillMaxWidth()<br>            ) {<br>                Text(<br>                    text = statusText,<br>                    style = MaterialTheme.typography.bodySmall,<br>                    fontWeight = FontWeight.Medium,<br>                    color = statusContentColor,<br>                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)<br>                )<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>private fun AuthActionCard(<br>    uiState: BiometricUiState,<br>    onAuthenticate: () -&gt; Unit,<br>    onLogout: () -&gt; Unit<br>) {<br>    val isAvailable = uiState.biometricStatus is BiometricStatus.Available<br>    val isAuthenticating = uiState.authState is AuthState.Authenticating<br><br>    Card(<br>        modifier = Modifier.fillMaxWidth(),<br>        shape = RoundedCornerShape(20.dp),<br>        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)<br>    ) {<br>        Column(<br>            modifier = Modifier<br>                .padding(20.dp)<br>                .fillMaxWidth(),<br>            horizontalAlignment = Alignment.CenterHorizontally<br>        ) {<br>            Text(<br>                text = if (uiState.isAuthenticated) &quot;Authenticated Session&quot; else &quot;Biometric Verification&quot;,<br>                style = MaterialTheme.typography.titleMedium,<br>                fontWeight = FontWeight.Bold<br>            )<br><br>            Spacer(modifier = Modifier.height(16.dp))<br><br>            // Fingerprint scanner button<br>            val scannerBg by animateColorAsState(<br>                targetValue = when {<br>                    uiState.isAuthenticated -&gt; Color(0xFF4CAF50)<br>                    uiState.authState is AuthState.Error -&gt; Color(0xFFE53935)<br>                    isAuthenticating -&gt; MaterialTheme.colorScheme.secondary<br>                    else -&gt; MaterialTheme.colorScheme.primary<br>                }<br>            )<br><br>            Box(<br>                modifier = Modifier<br>                    .size(96.dp)<br>                    .clip(CircleShape)<br>                    .background(scannerBg)<br>                    .clickable(enabled = isAvailable &amp;&amp; !isAuthenticating &amp;&amp; !uiState.isAuthenticated) {<br>                        onAuthenticate()<br>                    },<br>                contentAlignment = Alignment.Center<br>            ) {<br>                if (isAuthenticating) {<br>                    CircularProgressIndicator(<br>                        color = Color.White,<br>                        modifier = Modifier.size(48.dp),<br>                        strokeWidth = 3.dp<br>                    )<br>                } else {<br>                    FingerprintCanvasIcon(<br>                        modifier = Modifier.size(56.dp),<br>                        color = Color.White<br>                    )<br>                }<br>            }<br><br>            Spacer(modifier = Modifier.height(16.dp))<br><br>            // Auth status description text<br>            when (val state = uiState.authState) {<br>                is AuthState.Authenticating -&gt; {<br>                    Text(<br>                        text = &quot;Touch fingerprint sensor or scan face...&quot;,<br>                        style = MaterialTheme.typography.bodyMedium,<br>                        color = MaterialTheme.colorScheme.secondary,<br>                        fontWeight = FontWeight.Medium<br>                    )<br>                }<br>                is AuthState.Success -&gt; {<br>                    Text(<br>                        text = state.message,<br>                        style = MaterialTheme.typography.bodyMedium,<br>                        color = Color(0xFF2E7D32),<br>                        fontWeight = FontWeight.Bold<br>                    )<br>                }<br>                is AuthState.Error -&gt; {<br>                    Text(<br>                        text = state.message,<br>                        style = MaterialTheme.typography.bodyMedium,<br>                        color = MaterialTheme.colorScheme.error,<br>                        fontWeight = FontWeight.Medium,<br>                        textAlign = TextAlign.Center<br>                    )<br>                }<br>                is AuthState.Idle -&gt; {<br>                    Text(<br>                        text = if (uiState.isAuthenticated)<br>                            &quot;Access granted to secure features.&quot;<br>                        else if (isAvailable)<br>                            &quot;Tap icon or button below to scan fingerprint&quot;<br>                        else<br>                            &quot;Biometrics unavailable on this device&quot;,<br>                        style = MaterialTheme.typography.bodySmall,<br>                        color = MaterialTheme.colorScheme.onSurfaceVariant,<br>                        textAlign = TextAlign.Center<br>                    )<br>                }<br>            }<br><br>            Spacer(modifier = Modifier.height(16.dp))<br><br>            if (!uiState.isAuthenticated) {<br>                Button(<br>                    onClick = onAuthenticate,<br>                    enabled = isAvailable &amp;&amp; !isAuthenticating,<br>                    modifier = Modifier.fillMaxWidth(),<br>                    shape = RoundedCornerShape(12.dp)<br>                ) {<br>                    Text(<br>                        text = if (isAuthenticating) &quot;Authenticating...&quot; else &quot;Authenticate with Fingerprint&quot;,<br>                        fontWeight = FontWeight.Bold,<br>                        modifier = Modifier.padding(vertical = 4.dp)<br>                    )<br>                }<br>            } else {<br>                Row(<br>                    modifier = Modifier.fillMaxWidth(),<br>                    horizontalArrangement = Arrangement.spacedBy(12.dp)<br>                ) {<br>                    OutlinedButton(<br>                        onClick = onAuthenticate,<br>                        modifier = Modifier.weight(1f),<br>                        shape = RoundedCornerShape(12.dp)<br>                    ) {<br>                        Text(&quot;Verify Again&quot;)<br>                    }<br>                    Button(<br>                        onClick = onLogout,<br>                        modifier = Modifier.weight(1f),<br>                        shape = RoundedCornerShape(12.dp),<br>                        colors = ButtonDefaults.buttonColors(<br>                            containerColor = MaterialTheme.colorScheme.error<br>                        )<br>                    ) {<br>                        Text(&quot;Lock Vault&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>private fun SecretVaultCard(secretData: String) {<br>    Card(<br>        modifier = Modifier.fillMaxWidth(),<br>        shape = RoundedCornerShape(16.dp),<br>        colors = CardDefaults.cardColors(<br>            containerColor = Color(0xFFE8F5E9)<br>        )<br>    ) {<br>        Column(<br>            modifier = Modifier.padding(16.dp)<br>        ) {<br>            Row(verticalAlignment = Alignment.CenterVertically) {<br>                Text(<br>                    text = &quot;? Unlocked Vault Content&quot;,<br>                    style = MaterialTheme.typography.titleMedium,<br>                    fontWeight = FontWeight.Bold,<br>                    color = Color(0xFF1B5E20)<br>                )<br>            }<br>            Spacer(modifier = Modifier.height(8.dp))<br>            Text(<br>                text = &quot;Protected Data Payload:&quot;,<br>                style = MaterialTheme.typography.bodySmall,<br>                color = Color(0xFF2E7D32)<br>            )<br>            Spacer(modifier = Modifier.height(4.dp))<br>            Surface(<br>                shape = RoundedCornerShape(8.dp),<br>                color = Color.White,<br>                modifier = Modifier.fillMaxWidth()<br>            ) {<br>                Text(<br>                    text = secretData,<br>                    fontFamily = FontFamily.Monospace,<br>                    fontSize = 12.sp,<br>                    color = Color(0xFF1B5E20),<br>                    modifier = Modifier.padding(12.dp)<br>                )<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>private fun LogSectionHeader(<br>    logCount: Int,<br>    onClearLogs: () -&gt; Unit<br>) {<br>    Row(<br>        modifier = Modifier.fillMaxWidth(),<br>        horizontalArrangement = Arrangement.SpaceBetween,<br>        verticalAlignment = Alignment.CenterVertically<br>    ) {<br>        Text(<br>            text = &quot;Authentication Audit Logs ($logCount)&quot;,<br>            style = MaterialTheme.typography.titleMedium,<br>            fontWeight = FontWeight.Bold<br>        )<br>        if (logCount &gt; 0) {<br>            OutlinedButton(<br>                onClick = onClearLogs,<br>                shape = RoundedCornerShape(12.dp)<br>            ) {<br>                Text(&quot;Clear&quot;, fontSize = 12.sp)<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>private fun EmptyLogCard() {<br>    OutlinedCard(<br>        modifier = Modifier.fillMaxWidth(),<br>        shape = RoundedCornerShape(12.dp)<br>    ) {<br>        Box(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .padding(24.dp),<br>            contentAlignment = Alignment.Center<br>        ) {<br>            Text(<br>                text = &quot;No authentication attempts recorded yet.&quot;,<br>                style = MaterialTheme.typography.bodyMedium,<br>                color = MaterialTheme.colorScheme.onSurfaceVariant<br>            )<br>        }<br>    }<br>}<br><br>@Composable<br>private fun LogEntryRow(entry: AuthLogEntry) {<br>    Card(<br>        modifier = Modifier.fillMaxWidth(),<br>        shape = RoundedCornerShape(12.dp),<br>        colors = CardDefaults.cardColors(<br>            containerColor = if (entry.isSuccess) Color(0xFFF1F8E9) else Color(0xFFFFEBEE)<br>        )<br>    ) {<br>        Row(<br>            modifier = Modifier<br>                .padding(12.dp)<br>                .fillMaxWidth(),<br>            horizontalArrangement = Arrangement.SpaceBetween,<br>            verticalAlignment = Alignment.CenterVertically<br>        ) {<br>            Column(modifier = Modifier.weight(1f)) {<br>                Row(verticalAlignment = Alignment.CenterVertically) {<br>                    Text(<br>                        text = entry.status,<br>                        style = MaterialTheme.typography.bodySmall,<br>                        fontWeight = FontWeight.Bold,<br>                        color = if (entry.isSuccess) Color(0xFF2E7D32) else Color(0xFFC62828)<br>                    )<br>                    Spacer(modifier = Modifier.width(8.dp))<br>                    Text(<br>                        text = entry.timeString,<br>                        style = MaterialTheme.typography.labelSmall,<br>                        color = Color.Gray<br>                    )<br>                }<br>                Spacer(modifier = Modifier.height(2.dp))<br>                Text(<br>                    text = entry.details,<br>                    style = MaterialTheme.typography.bodySmall,<br>                    color = MaterialTheme.colorScheme.onSurface<br>                )<br>            }<br>        }<br>    }<br>}<br><br>@Composableshared/src/commonMain/kotlin/.../ui/BiometricAuthScreen.ktshared/src/commonMain/kotlin/.../ui/BiometricAuthScreen.ktshared/src/commonMain/kotlin/.../ui/BiometricAuthScreen.kt<br>private fun FingerprintCanvasIcon(<br>    modifier: Modifier = Modifier,<br>    color: Color = Color.White<br>) {<br>    Canvas(modifier = modifier) {<br>        val w = size.width<br>        val h = size.height<br><br>        val strokeWidth = w * 0.08f<br><br>        // Draw concentric fingerprint arches<br>        drawArc(<br>            color = color,<br>            startAngle = 180f,<br>            sweepAngle = 180f,<br>            useCenter = false,<br>            topLeft = androidx.compose.ui.geometry.Offset(w * 0.1f, h * 0.15f),<br>            size = androidx.compose.ui.geometry.Size(w * 0.8f, h * 0.8f),<br>            style = Stroke(width = strokeWidth)<br>        )<br><br>        drawArc(<br>            color = color,<br>            startAngle = 180f,<br>            sweepAngle = 180f,<br>            useCenter = false,<br>            topLeft = androidx.compose.ui.geometry.Offset(w * 0.25f, h * 0.3f),<br>            size = androidx.compose.ui.geometry.Size(w * 0.5f, h * 0.5f),<br>            style = Stroke(width = strokeWidth)<br>        )<br><br>        drawArc(<br>            color = color,<br>            startAngle = 180f,<br>            sweepAngle = 180f,<br>            useCenter = false,<br>            topLeft = androidx.compose.ui.geometry.Offset(w * 0.38f, h * 0.45f),<br>            size = androidx.compose.ui.geometry.Size(w * 0.24f, h * 0.24f),<br>            style = Stroke(width = strokeWidth)<br>        )<br><br>        // Center ridge line<br>        drawLine(<br>            color = color,<br>            start = androidx.compose.ui.geometry.Offset(w * 0.5f, h * 0.57f),<br>            end = androidx.compose.ui.geometry.Offset(w * 0.5f, h * 0.85f),<br>            strokeWidth = strokeWidth<br>        )<br><br>        // Outer side ridges<br>        drawLine(<br>            color = color,<br>            start = androidx.compose.ui.geometry.Offset(w * 0.25f, h * 0.55f),<br>            end = androidx.compose.ui.geometry.Offset(w * 0.25f, h * 0.85f),<br>            strokeWidth = strokeWidth<br>        )<br><br>        drawLine(<br>            color = color,<br>            start = androidx.compose.ui.geometry.Offset(w * 0.75f, h * 0.55f),<br>            end = androidx.compose.ui.geometry.Offset(w * 0.75f, h * 0.85f),<br>            strokeWidth = strokeWidth<br>        )<br>    }<br>}</pre><pre>// shared/src/commonMain/kotlin/.../App.kt<br>package com.biometric.authenticator<br><br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.tooling.preview.Preview<br>import com.biometric.authenticator.ui.BiometricAuthScreen<br><br>@Composable<br>@Preview<br>fun App() {<br>    MaterialTheme {<br>        BiometricAuthScreen()<br>    }<br>}</pre><h3><strong>Conclusion</strong></h3><p>Kotlin Multiplatform and Compose Multiplatform deliver an unprecedented developer experience. We were able to implement native, hardware-level biometric authentication for both Android and iOS while sharing 100% of our domain models, ViewModel state logic, and Compose UI. Whether you are building enterprise banking apps or consumer utilities, adopting KMP guarantees platform compliance, native security performance, and immense code reuse.</p><p>📦 <strong>GitHub Repository:</strong> <a href="https://github.com/karttiktungenwar/BiometricAuthenticator">karttiktungenwar/BiometricAuthenticator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c80095bba1d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Cross-Platform Aadhaar Face Authentication App in Flutter Using Clean Architecture]]></title>
            <link>https://medium.com/@tungenwarkartick/building-a-cross-platform-aadhaar-face-authentication-app-in-flutter-using-clean-architecture-1fd19ee10f07?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fd19ee10f07</guid>
            <category><![CDATA[aadhaar-face-auth]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 15:31:31 GMT</pubDate>
            <atom:updated>2026-07-22T15:32:42.425Z</atom:updated>
            <content:encoded><![CDATA[<p>In high-security fintech and government digital identity solutions, verifying user identity seamlessly across both Android and iOS devices is critical. UIDAI’s <strong>Aadhaar Face Authentication</strong> provides a contactless, secure, and highly accessible biometric mechanism that eliminates the need for external fingerprint hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFUYsxKMjitVdmov9cOs-w.png" /></figure><p>When implementing biometric capture natively via Platform Channels or UIDAI FaceRD packages, structuring your codebase with <strong>Clean Architecture</strong> keeps your business rules decoupled from Flutter UI widgets and low-level platform APIs.</p><p>This guide provides a production-grade, publication-ready draft for your Medium article, complete with explicit file structures and complete code blocks referencing the <a href="https://github.com/karttiktungenwar/aadhaar_face_auth">karttiktungenwar/aadhaar_face_auth</a> repository.</p><h3>Architecture Blueprint</h3><p>Clean Architecture separates your app into three distinct layers, ensuring each layer depends only on abstraction interfaces rather than concrete details.</p><pre>┌───────────────────────────────────────────────────────────┐<br>│                    Presentation Layer                     │<br>│               (Widgets, Pages, BLoC State)                │<br>└─────────────────────────────┬─────────────────────────────┘<br>                              │<br>                              ▼<br>┌───────────────────────────────────────────────────────────┐<br>│                       Domain Layer                        │<br>│            (Entities, Use Cases, Failures)                │<br>└─────────────────────────────▲─────────────────────────────┘<br>                              │<br>┌─────────────────────────────┴─────────────────────────────┐<br>│                        Data Layer                         │<br>│       (Platform Channels, Remote APIs, Repositories)      │<br>└───────────────────────────────────────────────────────────┘</pre><h3>Directory &amp; File Structure</h3><p>Here is the complete project structure tailored for cross-platform Aadhaar Face Authentication:</p><p>lib/<br>├── main.dart<br>└── src/<br> ├── app/<br> │ └── di/<br> │ └── injection_container.dart<br> ├── core/<br> │ ├── enums/<br> │ │ └── status.dart<br> │ ├── error/<br> │ │ └── failures.dart<br> │ └── utill/<br> │ └── aadhaar_validator.dart<br> └── features/<br> └── aadhaar/<br> ├── data/<br> │ └── repository/<br> │ └── face_rd_repository_impl.dart<br> ├── domain/<br> │ ├── repository/<br> │ │ └── face_rd_repository.dart<br> │ └── useCase/<br> │ └── capture_face_rd_use_case.dart<br> └── presentation/<br> ├── bloc/<br> │ ├── face_rd_bloc.dart<br> │ ├── face_rd_event.dart<br> │ └── face_rd_state.dart<br> └── screens/<br> └── aadhaar_face_auth_screen.dart</p><p>Here is the initial setup terminal command to generate a new Flutter project, followed by the exact pubspec.yaml configuration containing all dependencies for Clean Architecture and Aadhaar Face Authentication.</p><h4>1. Create the Flutter Project</h4><p>Run this command in your terminal to create the project with proper package domain naming:</p><pre>flutter create --org com.app aadhaar_face_auth_app<br>cd aadhaar_face_auth_app</pre><h3>2. Update pubspec.yaml</h3><p>Replace the contents of your project’s pubspec.yaml with this configuration. It includes state management (flutter_bloc), dependency injection (get_it), functional programming utilities (fpdart), value equality (equatable), and platform biometric libraries.</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br><br>  # --- State Management &amp; Dependency Injection ---<br>  equatable: ^2.1.0<br>  flutter_bloc: ^9.1.1<br>  get_it: ^9.2.1<br><br>  # --- Functional Programming ---<br>  dartz: ^0.10.1<br><br>  #--- Functional Biometric---<br>  aadhaar_face_rd: ^0.1.3<br>  url_launcher: ^6.3.0<br>  uuid: ^4.6.0<br>  permission_handler: ^11.3.1<br>  xml: ^7.0.1<br><br></pre><h3><strong>Step 1: Core Framework Contracts</strong></h3><ol><li>Status Enum</li></ol><pre>// lib/src/core/enums/status.dart<br>enum Status { initial, loading, success, error, appNotInstalled }</pre><p>2.Error</p><pre>// lib/src/core/error/failures.dart<br>import &#39;package:equatable/equatable.dart&#39;;<br><br>abstract class Failure extends Equatable {<br>  final String message;<br>  const Failure(this.message);<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [message];<br>}<br><br>class ServerFailure extends Failure {<br>  const ServerFailure([super.message = &#39;Internal Server Error&#39;]);<br>}<br><br>class NetworkFailure extends Failure {<br>  const NetworkFailure([super.message = &#39;No Internet Connection&#39;]);<br>}<br><br>class AuthFailure extends Failure {<br>  const AuthFailure([super.message = &#39;Authentication Failed&#39;]);<br>}<br><br>class PermissionFailure extends Failure {<br>  const PermissionFailure([super.message = &#39;Permission Denied&#39;]);<br>}<br><br>class ValidationFailure extends Failure {<br>  const ValidationFailure(super.message);<br>}<br><br>class PlatformFailure extends Failure {<br>  final String code; // e.g., &#39;PERMISSION_DENIED&#39;, &#39;SETTINGS_NOT_FOUND&#39;<br><br>  const PlatformFailure({required this.code, required String message})<br>    : super(message);<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [code, message];<br>}</pre><p>3.Utill</p><pre>// lib/src/core/utill/aadhaar_validator.dart<br>class AadhaarValidator {<br>  static final List&lt;List&lt;int&gt;&gt; _d = [<br>    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],<br>    [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],<br>    [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],<br>    [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],<br>    [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],<br>    [5, 9, 8, 7, 6, 0, 1, 2, 3, 4],<br>    [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],<br>    [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],<br>    [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],<br>    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]<br>  ];<br><br>  static final List&lt;List&lt;int&gt;&gt; _p = [<br>    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],<br>    [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],<br>    [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],<br>    [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],<br>    [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],<br>    [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],<br>    [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],<br>    [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]<br>  ];<br><br>  static bool isValid(String aadhaarNumber) {<br>    final RegExp regExp = RegExp(r&#39;^[2-9][0-9]{11}$&#39;);<br>    if (!regExp.hasMatch(aadhaarNumber)) return false;<br><br>    int checksum = 0;<br>    List&lt;int&gt; digits = aadhaarNumber.codeUnits.map((e) =&gt; e - 48).toList().reversed.toList();<br><br>    for (int i = 0; i &lt; digits.length; i++) {<br>      checksum = _d[checksum][_p[i % 8][digits[i]]];<br>    }<br><br>    return checksum == 0;<br>  }<br>}</pre><h3>Step 2: Domain Layer (Business Logic)</h3><p>The Domain Layer defines what your app does without importing any UI elements or platform-specific packages.</p><p>1.Repository</p><pre>// lib/src/features/aadhaar/data/repository/face_rd_repository.dart<br>abstract class FaceRdRepository {<br>  Stream&lt;Either&lt;Failure, String&gt;&gt; get faceRdStream;<br>  Future&lt;bool&gt; checkIsInstalled();<br>  Future&lt;void&gt; captureFace({required String pidOptionsXml});<br>  void dispose();<br>}</pre><p>2.Usecase</p><pre>// lib/src/features/aadhaar/domain/useCase/capture_face_rd_use_case.dart<br>class CaptureFaceRdUseCase {<br>  final FaceRdRepository repository;<br><br>  CaptureFaceRdUseCase({required this.repository});<br><br>  Stream&lt;Either&lt;Failure, String&gt;&gt; get responseStream =&gt; repository.faceRdStream;<br><br>  Future&lt;void&gt; execute({required String pidOptionsXml}) async {<br>    final isInstalled = await repository.checkIsInstalled();<br>    if (!isInstalled) {<br>      throw Exception(&quot;Face RD Service app is not installed on this device.&quot;);<br>    }<br>    await repository.captureFace(pidOptionsXml: pidOptionsXml);<br>  }<br><br>  void dispose() =&gt; repository.dispose();<br>}</pre><h3>Step 3: Data Layer (Platform Channels)</h3><p>The Data Layer handles the actual platform communication (such as launching the UIDAI FaceRD intent on Android or handling headless URLs on iOS).</p><pre>//lib/src/features/aadhaar/data/repository/face_rd_repository_impl.dart<br>class FaceRdRepositoryImpl implements FaceRdRepository {<br>  final AadhaarFaceRd _faceRd;<br>  final StreamController&lt;Either&lt;Failure, String&gt;&gt; _controller =<br>  StreamController&lt;Either&lt;Failure, String&gt;&gt;.broadcast();<br><br>  StreamSubscription&lt;String?&gt;? _subscription;<br><br>  FaceRdRepositoryImpl({AadhaarFaceRd? faceRd})<br>      : _faceRd = faceRd ?? AadhaarFaceRd() {<br>    // Listen to the plugin stream and map it to Either&lt;Failure, Success&gt;<br>    _subscription = _faceRd.onResponse.listen(<br>          (response) {<br>        if (response != null &amp;&amp; response.isNotEmpty) {<br>          // Success case: The XML contains errCode=&quot;0&quot;<br>          try {<br>            final document = XmlDocument.parse(response);<br>            final respElement = document.findAllElements(&#39;Resp&#39;).firstOrNull;<br><br>            if (respElement == null) {<br>              _controller.add(const Left(ValidationFailure(&#39;Invalid response format: Missing &lt;Resp&gt; tag&#39;)));<br>              return;<br>            }<br><br>            final errCode = respElement.getAttribute(&#39;errCode&#39;) ?? &#39;-1&#39;;<br>            final errInfo = respElement.getAttribute(&#39;errInfo&#39;) ?? &#39;Unknown error&#39;;<br><br>            if (errCode == &#39;0&#39;) {<br>              _controller.add(Right(response));<br>            } else {<br>              _controller.add(Left(PlatformFailure(code: errCode, message: errInfo)));<br>            }<br>          } catch (e) {<br>            _controller.add(Left(ValidationFailure(&#39;XML Parse Error: ${e.toString()}&#39;)));<br>          }<br>        } else {<br>          _controller.add(const Left(ValidationFailure(&quot;Face capture canceled or empty response.&quot;)));<br>        }<br>      },<br>      onError: (error) {<br>        _controller.add(Left(PlatformFailure(code: &#39;STREAM_ERROR&#39;, message: error.toString())));<br>      },<br>    );<br>  }<br><br>  @override<br>  Stream&lt;Either&lt;Failure, String&gt;&gt; get faceRdStream =&gt; _controller.stream;<br><br>  @override<br>  Future&lt;bool&gt; checkIsInstalled() async {<br>    return await _faceRd.isFaceRDInstalled();<br>  }<br><br>  @override<br>  Future&lt;void&gt; captureFace({required String pidOptionsXml}) async {<br>    await _faceRd.launchFaceRd(pidOptionsXml: pidOptionsXml);<br>  }<br><br>  @override<br>  void dispose() {<br>    _subscription?.cancel();<br>    _controller.close();<br>    _faceRd.dispose();<br>  }<br>}</pre><h3>Step 4: Presentation Layer (BLoC State Management)</h3><p>1.State Bloc</p><pre>// lib/src/features/aadhaar/presentation/bloc/face_rd_state.dart<br>part of &#39;face_rd_bloc.dart&#39;;<br><br>class FaceRdState extends Equatable {<br>  final Status status;<br>  final String? pidXml;<br>  final String? error;<br><br>  const FaceRdState({<br>    this.status = Status.initial,<br>    this.pidXml,<br>    this.error,<br>  });<br><br><br>  /// CopyWith method to update state properties immutably<br>  FaceRdState copyWith({<br>    Status? status,<br>    String? pidXml,<br>    String? error,<br>  }) {<br>    return FaceRdState(<br>      status: status ?? this.status,<br>      pidXml: pidXml ?? this.pidXml,<br>      error: error ?? this.error,<br>    );<br>  }<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [status, pidXml, error];<br>}</pre><p>2.Event Bloc</p><pre>// lib/src/features/aadhaar/presentation/bloc/face_rd_event.dart<br>part of &#39;face_rd_bloc.dart&#39;;<br><br>abstract class FaceRdEvent {<br>}<br><br>class StartFaceCaptureEvent extends FaceRdEvent {<br>  final String pidOptionsXml;<br><br>  StartFaceCaptureEvent({required this.pidOptionsXml});<br>}<br><br>class InternalFaceRdResultReceived extends FaceRdEvent {<br>  final Either&lt;Failure, String&gt; result;<br><br>  InternalFaceRdResultReceived(this.result);<br>}<br><br>class ResetFaceRdEvent extends FaceRdEvent {}</pre><p>3.Main Bloc</p><pre>// lib/src/features/aadhaar/presentation/bloc/face_rd_bloc.dart<br>part &#39;face_rd_event.dart&#39;;<br>part &#39;face_rd_state.dart&#39;;<br><br>class FaceRdBloc extends Bloc&lt;FaceRdEvent, FaceRdState&gt; {<br>  final CaptureFaceRdUseCase captureFaceRdUseCase;<br>  StreamSubscription? _streamSubscription;<br><br>  FaceRdBloc({required this.captureFaceRdUseCase}) : super(const FaceRdState()) {<br>    on&lt;StartFaceCaptureEvent&gt;(_onStartCapture);<br>    on&lt;InternalFaceRdResultReceived&gt;(_onResultReceived);<br>    on&lt;ResetFaceRdEvent&gt;((event, emit) =&gt; emit(const FaceRdState()));<br><br>    // Subscribe to stream output from use case<br>    _streamSubscription = captureFaceRdUseCase.responseStream.listen((result) {<br>      add(InternalFaceRdResultReceived(result));<br>    });<br>  }<br><br>  Future&lt;void&gt; _onStartCapture(<br>      StartFaceCaptureEvent event,<br>      Emitter&lt;FaceRdState&gt; emit,<br>      ) async {<br>    emit(state.copyWith(status: Status.loading));<br>    try {<br>      await captureFaceRdUseCase.execute(pidOptionsXml: event.pidOptionsXml);<br>    } catch (e) {<br>      debugPrint(&quot;Error in _onStartCapture: $e&quot;);<br>      emit(state.copyWith(status: Status.appNotInstalled));<br>    }<br>  }<br><br>  void _onResultReceived(<br>      InternalFaceRdResultReceived event,<br>      Emitter&lt;FaceRdState&gt; emit,<br>      ) {<br>    event.result.fold(<br>          (failure) =&gt; {<br>            emit(state.copyWith(status: Status.error, error: failure.message))<br>          },<br>          (pidXml) =&gt; {<br>            emit(state.copyWith(status: Status.success, pidXml: pidXml))<br>          },<br>    );<br>  }<br><br>  @override<br>  Future&lt;void&gt; close() {<br>    _streamSubscription?.cancel();<br>    captureFaceRdUseCase.dispose();<br>    return super.close();<br>  }<br>}</pre><p>4.Screen</p><pre>// lib/src/features/aadhaar/presentation/screens/aadhaar_face_auth_screen.dart<br>class AadhaarFaceAuthScreen extends StatelessWidget {<br>  const AadhaarFaceAuthScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    // Provide the FaceRdBloc to the widget subtree<br>    return BlocProvider&lt;FaceRdBloc&gt;(<br>      create: (context) =&gt; sl&lt;FaceRdBloc&gt;(),<br>      child: const AadhaarFaceAuthView(),<br>    );<br>  }<br>}<br><br>class AadhaarFaceAuthView extends StatefulWidget {<br>  const AadhaarFaceAuthView({super.key});<br><br>  @override<br>  State&lt;AadhaarFaceAuthView&gt; createState() =&gt; _AadhaarFaceAuthViewState();<br>}<br><br>class _AadhaarFaceAuthViewState extends State&lt;AadhaarFaceAuthView&gt; {<br>  final TextEditingController _aadhaarController = TextEditingController();<br><br>  @override<br>  void dispose() {<br>    _aadhaarController.dispose();<br>    super.dispose();<br>  }<br><br>  Future&lt;void&gt; openAadhaarFaceRdPlayStore() async {<br>    // Official UIDAI Face RD App package name on Google Play Store<br>    const packageName = &#39;in.gov.uidai.facerd&#39;;<br>    final Uri playStoreUri = Uri.parse(&#39;market://details?id=$packageName&#39;);<br>    final Uri webUri = Uri.parse(<br>        &#39;https://play.google.com/store/apps/details?id=$packageName&#39;);<br><br>    if (await canLaunchUrl(playStoreUri)) {<br>      await launchUrl(playStoreUri);<br>    } else if (await canLaunchUrl(webUri)) {<br>      await launchUrl(webUri, mode: LaunchMode.externalApplication);<br>    }<br>  }<br><br>  /// Constructs the standard PID Options XML string.<br>  String buildPidOptionsXml({<br>    required String txnId,<br>    required String environment,<br>    String wadh = &quot;sgydIC09zzy6f8Lb3xaAqzKquKe9lFcNR9uTvYxFp+A=&quot;,<br>    String purpose = &quot;ekyc&quot;,<br>    String language = &quot;en&quot;,<br>    bool enableAutoCapture = true,<br>    bool enableImageScoreSheet = true,<br>    required String cameraUsage,<br>  }) {<br>    try {<br>      final xml = &#39;&#39;&#39;<br>    &lt;PidOptions ver=&quot;1.0&quot; env=&quot;$environment&quot;&gt;<br>      &lt;Opts<br>        fCount=&quot;&quot;<br>        fType=&quot;&quot;<br>        iCount=&quot;&quot;<br>        iType=&quot;&quot;<br>        pCount=&quot;&quot;<br>        pType=&quot;&quot;<br>        format=&quot;&quot;<br>        pidVer=&quot;2.0&quot;<br>        timeout=&quot;&quot;<br>        otp=&quot;&quot;<br>        posh=&quot;&quot;<br>        wadh=&quot;$wadh&quot;<br>      /&gt;<br>      &lt;CustOpts&gt;<br>        &lt;Param name=&quot;txnId&quot; value=&quot;$txnId&quot;/&gt;<br>        &lt;Param name=&quot;purpose&quot; value=&quot;$purpose&quot;/&gt;<br>        &lt;Param name=&quot;language&quot; value=&quot;$language&quot;/&gt;<br>        &lt;Param name=&quot;enableAutoCapture&quot; value=&quot;${enableAutoCapture ? &#39;true&#39; : &#39;false&#39;}&quot;/&gt;<br>        &lt;Param name=&quot;enableImageScoreSheet&quot; value=&quot;${enableImageScoreSheet ? &#39;true&#39; : &#39;false&#39;}&quot;/&gt;<br>        &lt;Param name=&quot;cameraUsage&quot; value=&quot;$cameraUsage&quot;/&gt;<br>      &lt;/CustOpts&gt;<br>    &lt;/PidOptions&gt;<br>    &#39;&#39;&#39;;<br>      // Remove newlines and extra spaces<br>      return xml.replaceAll(RegExp(r&#39;[\r\n]+&#39;), &#39; &#39;).trim();<br>    } catch (e) {<br>      debugPrint(&quot;Error building PID Options XML: $e&quot;);<br>      return &quot;ERROR :- ${e.toString()}&quot;;<br>    }<br>  }<br><br><br>  Future&lt;void&gt; _onVerifyPressed(BuildContext context) async {<br>    final inputNumber = _aadhaarController.text.trim();<br><br>    if (inputNumber.length != 12) {<br>      ScaffoldMessenger.of(context).showSnackBar(<br>        const SnackBar(<br>          content: Text(&#39;Please enter a valid 12-digit number.&#39;),<br>          backgroundColor: Colors.orange,<br>        ),<br>      );<br>      return;<br>    }<br><br>    FocusScope.of(context).unfocus();<br><br>    final pidXmlOptions = buildPidOptionsXml(<br>      txnId: const Uuid().v4(),<br>      cameraUsage: &#39;F&#39;,<br>      environment: &#39;P&#39;,<br>    );<br>    context.read&lt;FaceRdBloc&gt;().add(<br>      StartFaceCaptureEvent(pidOptionsXml: pidXmlOptions),<br>    );<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;Aadhaar Face Authentication&quot;),<br>      ),<br>      body: BlocConsumer&lt;FaceRdBloc, FaceRdState&gt;(<br>        listener: (context, state) {<br>          if (state.status == Status.appNotInstalled) {<br>            showDialog(<br>              context: context,<br>              builder: (dialogContext) =&gt;<br>                  AlertDialog(<br>                    title: const Text(&#39;Aadhaar Face RD Required&#39;),<br>                    content: const Text(<br>                      &#39;The official Aadhaar Face RD app is not installed on this device. &#39;<br>                          &#39;Please install it from the Google Play Store to continue.&#39;,<br>                    ),<br>                    actions: [<br>                      TextButton(<br>                        onPressed: () =&gt; Navigator.pop(dialogContext),<br>                        child: const Text(&#39;Cancel&#39;),<br>                      ),<br>                      ElevatedButton(<br>                        onPressed: () {<br>                          Navigator.pop(dialogContext);<br>                          openAadhaarFaceRdPlayStore();<br>                        },<br>                        child: const Text(&#39;Install from Play Store&#39;),<br>                      ),<br>                    ],<br>                  ),<br>            );<br>          }<br>          if (state.status == Status.error) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              SnackBar(<br>                content: Text(&#39;Error: ${state.error}&#39;),<br>                backgroundColor: Colors.red,<br>              ),<br>            );<br>          } else if (state.status == Status.success) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              const SnackBar(<br>                content: Text(&#39;Face capture completed successfully!&#39;),<br>                backgroundColor: Colors.green,<br>              ),<br>            );<br>          }<br>        },<br>        builder: (context, state) {<br>          final bool isLoading = state.status == Status.loading;<br><br>          return Padding(<br>            padding: const EdgeInsets.all(16.0),<br>            child: Column(<br>              crossAxisAlignment: CrossAxisAlignment.stretch,<br>              children: [<br>                TextField(<br>                  controller: _aadhaarController,<br>                  keyboardType: TextInputType.number,<br>                  maxLength: 12,<br>                  enabled: !isLoading,<br>                  onChanged: (value) {<br>                    if (state.status == Status.success || state.status == Status.error) {<br>                      context.read&lt;FaceRdBloc&gt;().add(ResetFaceRdEvent());<br>                    }<br>                  },<br>                  decoration: const InputDecoration(<br>                    labelText: &quot;Enter 12-digit Aadhaar Number&quot;,<br>                    border: OutlineInputBorder(),<br>                    prefixIcon: Icon(Icons.fingerprint),<br>                  ),<br>                ),<br>                const SizedBox(height: 20),<br>                ElevatedButton.icon(<br>                  onPressed: isLoading ? null : () =&gt; _onVerifyPressed(context),<br>                  icon: isLoading<br>                      ? const SizedBox(<br>                    width: 20,<br>                    height: 20,<br>                    child: CircularProgressIndicator(strokeWidth: 2),<br>                  )<br>                      : const Icon(Icons.camera_front),<br>                  label: Text(<br>                    isLoading ? &quot;Launching FaceRD...&quot; : &quot;Verify with FaceRD&quot;,<br>                  ),<br>                  style: ElevatedButton.styleFrom(<br>                    padding: const EdgeInsets.symmetric(vertical: 14),<br>                  ),<br>                ),<br>                const SizedBox(height: 24),<br>                _buildStatusCard(context, state),<br>              ],<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br><br>  Widget _buildStatusCard(BuildContext context, FaceRdState state) {<br>    String statusText = &#39;Status: Waiting for input&#39;;<br>    Color statusColor = Colors.grey;<br>    bool showCopyButton = false;<br>    String? pidXmlToCopy;<br><br>    if (state.status == Status.loading) {<br>      statusText = &#39;Status: Launching RD Service...&#39;;<br>      statusColor = Colors.blue;<br>    } else if (state.status == Status.success) {<br>      statusText =<br>      &#39;Status: Capture Success!\nPID Length: ${state.pidXml?.length} chars&#39;;<br>      statusColor = Colors.green;<br>      showCopyButton = true;<br>      pidXmlToCopy = state.pidXml;<br>    } else if (state.status == Status.error) {<br>      debugPrint(&quot;FaceRdFailure: ${state.error}&quot;);<br>      statusText = &#39;Status: Failed - ${state.error}&#39;;<br>      showCopyButton = true;<br>      pidXmlToCopy = state.error;<br>      statusColor = Colors.red;<br>    }<br><br>    return Card(<br>      color: statusColor.withAlpha(25),<br>      shape: RoundedRectangleBorder(<br>        side: BorderSide(color: statusColor, width: 1.5),<br>        borderRadius: BorderRadius.circular(12),<br>      ),<br>      child: Padding(<br>        padding: const EdgeInsets.all(16.0),<br>        child: Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          mainAxisSize: MainAxisSize.min,<br>          children: [<br>            Row(<br>              children: [<br>                Expanded(<br>                  child: Text(<br>                    statusText,<br>                    maxLines: 2,<br>                    style: TextStyle(<br>                      fontSize: 14,<br>                      fontWeight: FontWeight.w600,<br>                      color: statusColor,<br>                    ),<br>                  ),<br>                ),<br>                if (showCopyButton &amp;&amp; pidXmlToCopy != null)<br>                  IconButton(<br>                    icon: const Icon(Icons.copy_rounded),<br>                    color: statusColor,<br>                    tooltip: &#39;Copy PID Data&#39;,<br>                    onPressed: () =&gt; _copyToClipboard(context, pidXmlToCopy!),<br>                  ),<br>              ],<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br><br>  void _copyToClipboard(BuildContext context, String text) {<br>    Clipboard.setData(ClipboardData(text: text)).then((_) {<br>      if (context.mounted) {<br>        ScaffoldMessenger.of(context).showSnackBar(<br>          const SnackBar(<br>            content: Text(&#39;PID XML copied to clipboard!&#39;),<br>            duration: Duration(seconds: 2),<br>            behavior: SnackBarBehavior.floating,<br>          ),<br>        );<br>      }<br>    });<br>  }<br>}</pre><h3>Step 5: Android &amp; iOS Platform Setup</h3><h3>Android Setup (android/app/src/main/AndroidManifest.xml)</h3><p>On Android 11+ (API level 30+), you must explicitly declare package visibility for UIDAI’s in.gov.uidai.facerd service:</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;uses-permission android:permission=&quot;android.permission.CAMERA&quot; /&gt;<br>    &lt;uses-permission android:permission=&quot;android.permission.INTERNET&quot; /&gt;<br><br>    &lt;!-- Query UIDAI FaceRD Package on Android 11+ --&gt;<br>    &lt;queries&gt;<br>        &lt;package android:name=&quot;in.gov.uidai.facerd&quot; /&gt;<br>        &lt;intent&gt;<br>            &lt;action android:name=&quot;in.gov.uidai.rdservice.face.CAPTURE&quot; /&gt;<br>        &lt;/intent&gt;<br>    &lt;/queries&gt;<br>&lt;/manifest&gt;</pre><h3>iOS Setup (ios/Runner/Info.plist)</h3><p>Register application query schemes and usage descriptions:</p><pre>&lt;key&gt;NSCameraUsageDescription&lt;/key&gt;<br>&lt;string&gt;This application requires access to the camera for biometric face verification.&lt;/string&gt;<br><br>&lt;key&gt;LSApplicationQueriesSchemes&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;string&gt;FaceRDLib&lt;/string&gt;<br>&lt;/array&gt;</pre><h3>Step 6: Add DI</h3><p>This file acts as your Service Locator configuration. It registers your <strong>BLoc</strong>, <strong>Use Cases and Repositories </strong>in the correct dependency order.</p><pre>// lib/src/app/di/injection_container.dart<br>final sl = GetIt.instance;<br><br>Future&lt;void&gt; init() async {<br>  // Data Sources / Native Packages<br>  sl.registerLazySingleton&lt;AadhaarFaceRd&gt;(() =&gt; AadhaarFaceRd());<br><br>  // Repositories<br>  sl.registerLazySingleton&lt;FaceRdRepository&gt;(<br>        () =&gt; FaceRdRepositoryImpl(faceRd: sl&lt;AadhaarFaceRd&gt;()),<br>  );<br><br>  // Use Cases<br>  sl.registerLazySingleton&lt;CaptureFaceRdUseCase&gt;(<br>        () =&gt; CaptureFaceRdUseCase(repository: sl&lt;FaceRdRepository&gt;()),<br>  );<br><br>  // BLoCs (Always use registerFactory)<br>  sl.registerFactory&lt;FaceRdBloc&gt;(<br>        () =&gt; FaceRdBloc(captureFaceRdUseCase: sl&lt;CaptureFaceRdUseCase&gt;()),<br>  );<br>}</pre><h3>Step 7: Main</h3><p>In main.dart, we initialize the service locator before runApp() executes.</p><pre>// lib/main.dart<br>Future&lt;void&gt; main() async {<br>  await init();<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Aadhaar Face Authentication&#39;,<br>      theme: ThemeData(<br>        colorScheme: .fromSeed(seedColor: Colors.deepPurple),<br>      ),<br>      home: const AadhaarFaceAuthScreen(),<br>    );<br>  }<br>}</pre><h3>Summary</h3><p>By applying Clean Architecture, your application clearly separates business rules from platform dependencies, ensuring that future updates to UIDAI specs or platform channels don’t break your UI logic.</p><p>Check out the implementation details and native bridge source code at <a href="https://github.com/karttiktungenwar/aadhaar_face_auth">karttiktungenwar/aadhaar_face_auth on GitHub</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fd19ee10f07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Local Data Security: FlutterSecureStorage with Dependency Injection (GetIt)]]></title>
            <link>https://medium.com/@tungenwarkartick/mastering-local-data-security-fluttersecurestorage-with-dependency-injection-getit-e44c8f33889f?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e44c8f33889f</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 12:24:20 GMT</pubDate>
            <atom:updated>2026-07-08T12:24:20.699Z</atom:updated>
            <content:encoded><![CDATA[<p>When building production-grade Flutter applications, handling sensitive user data like access tokens, API keys, or biometric flags requires more than just standard local storage. Plain old shared_preferences writes data in clear text, making it vulnerable to reverse-engineering or device-rooting exploits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*8cqp-PA7_TGAjOnyw06kqA.png" /></figure><p>To secure this data, we turn to <strong>flutter_secure_storage</strong>, which utilizes <strong>Keychain</strong> on iOS and <strong>Keystore</strong> on Android. But as your app grows, instantiating this storage layer everywhere manually creates tightly coupled code that is a nightmare to test.</p><p>In this guide, we will look at how to build a clean, secure storage architecture by abstracting FlutterSecureStorage and registering it via <strong>Dependency Injection (DI)</strong> using get_it.</p><h3>Why Dependency Injection for Storage?</h3><p>Hardcoding const storage = FlutterSecureStorage(); across your features creates tight coupling. By utilizing Dependency Injection (DI), we unlock three core architectural benefits:</p><ol><li><strong>Single Source of Truth:</strong> One unified configuration for your encryption settings across the app.</li><li><strong>Testability:</strong> Easily swap the real secure storage with a mock class during unit testing.</li><li><strong>Decoupling:</strong> Your feature logic doesn’t care <em>how</em> data is saved; it just interacts with an abstract contract.</li></ol><h3>Step 1: Dependencies Setup</h3><p>Add the required packages to your pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_secure_storage: ^9.2.2 # Use the latest stable version<br>  get_it: ^8.0.3                  # For Dependency Injection</pre><h3>Step 2: Create a Storage Service Contract</h3><p>We will start by defining an abstract class. This acts as our interface, decoupling our application logic from the underlying storage implementation.</p><pre>import &#39;dart:convert&#39;; // Required for jsonEncode/jsonDecode<br>import &#39;package:flutter_secure_storage/flutter_secure_storage.dart&#39;;<br><br>abstract class SecureStorageService {<br>  // Write methods<br>  Future&lt;void&gt; writeString(String key, String value);<br>  Future&lt;void&gt; writeBool(String key, bool value);<br>  Future&lt;void&gt; writeInt(String key, int value);<br>  Future&lt;void&gt; writeDouble(String key, double value);<br>  Future&lt;void&gt; writeObject(String key, Map&lt;String, dynamic&gt; jsonMap);<br><br>  // Read methods<br>  Future&lt;String?&gt; readString(String key);<br>  Future&lt;bool?&gt; readBool(String key);<br>  Future&lt;int?&gt; readInt(String key);<br>  Future&lt;double?&gt; readDouble(String key);<br>  Future&lt;Map&lt;String, dynamic&gt;?&gt; readObject(String key);<br><br>  // Generic deletion<br>  Future&lt;void&gt; delete(String key);<br>  Future&lt;void&gt; clearAll();<br>}<br><br>class SecureStorageServiceImpl implements SecureStorageService {<br>  final FlutterSecureStorage _secureStorage;<br><br>  SecureStorageServiceImpl(this._secureStorage);<br><br>  // --- WRITE METHODS ---<br><br>  @override<br>  Future&lt;void&gt; writeString(String key, String value) async {<br>    await _secureStorage.write(key: key, value: value);<br>  }<br><br>  @override<br>  Future&lt;void&gt; writeBool(String key, bool value) async {<br>    await _secureStorage.write(key: key, value: value.toString());<br>  }<br><br>  @override<br>  Future&lt;void&gt; writeInt(String key, int value) async {<br>    await _secureStorage.write(key: key, value: value.toString());<br>  }<br><br>  @override<br>  Future&lt;void&gt; writeDouble(String key, double value) async {<br>    await _secureStorage.write(key: key, value: value.toString());<br>  }<br><br>  @override<br>  Future&lt;void&gt; writeObject(String key, Map&lt;String, dynamic&gt; jsonMap) async {<br>    final String jsonString = jsonEncode(jsonMap);<br>    await _secureStorage.write(key: key, value: jsonString);<br>  }<br><br>  // --- READ METHODS ---<br><br>  @override<br>  Future&lt;String?&gt; readString(String key) async {<br>    return await _secureStorage.read(key: key);<br>  }<br><br>  @override<br>  Future&lt;bool?&gt; readBool(String key) async {<br>    final value = await _secureStorage.read(key: key);<br>    if (value == null) return null;<br>    return value == &#39;true&#39;;<br>  }<br><br>  @override<br>  Future&lt;int?&gt; readInt(String key) async {<br>    final value = await _secureStorage.read(key: key);<br>    return value != null ? int.tryParse(value) : null;<br>  }<br><br>  @override<br>  Future&lt;double?&gt; readDouble(String key) async {<br>    final value = await _secureStorage.read(key: key);<br>    return value != null ? double.tryParse(value) : null;<br>  }<br><br>  @override<br>  Future&lt;Map&lt;String, dynamic&gt;?&gt; readObject(String key) async {<br>    final value = await _secureStorage.read(key: key);<br>    if (value == null) return null;<br>    try {<br>      return jsonDecode(value) as Map&lt;String, dynamic&gt;;<br>    } catch (_) {<br>      return null; // Handle malformed JSON gracefully<br>    }<br>  }<br><br>  // --- DELETE METHODS ---<br><br>  @override<br>  Future&lt;void&gt; delete(String key) async {<br>    await _secureStorage.delete(key: key);<br>  }<br><br>  @override<br>  Future&lt;void&gt; clearAll() async {<br>    await _secureStorage.deleteAll();<br>  }<br>}</pre><h3>Step 3: Setting Up Dependency Injection</h3><p>With our service ready, we configure GetIt to manage its lifecycle. We will register FlutterSecureStorage as a dependency, and then inject it into our implementation.</p><p>Create a file named locator.dart:</p><pre>import &#39;package:flutter_secure_storage/flutter_secure_storage.dart&#39;;<br>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:flutter_secure_storage/flutter_secure_storage.dart&#39;;<br>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;secure_storage_service.dart&#39;;<br><br>final sl = GetIt.instance;<br><br>Future&lt;void&gt; setupLocator() async {<br><br>  // 2. iOS Specific Options<br>  const iosOptions = IOSOptions(<br>  // Accessibility.first_unlock ensures data is accessible after the device restarts<br>  // but before the user unlocks it (crucial for background sync/push notifications).<br>  accessibility: KeychainAccessibility.first_unlock,<br>  // Prevents your app&#39;s sensitive keys from being backed up to iCloud<br>  synchronizable: false,<br>  );<br><br>  // 3. Instantiate FlutterSecureStorage with both options<br>  final secureStorage = FlutterSecureStorage(<br>  iOptions: iosOptions,<br>  );<br><br>  // 4. Register Service<br>  sl.registerLazySingleton&lt;SecureStorageService&gt;(<br>  () =&gt; SecureStorageServiceImpl(secureStorage),<br>  );<br><br>}</pre><p>Initialize your dependency graph inside your app’s main.dart before triggering runApp:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;locator.dart&#39;;<br><br>void main() {<br>  // Ensure Flutter bindings are initialized<br>  WidgetsFlutterBinding.ensureInitialized();<br>  <br>  // Setup DI locator<br>  awit setupLocator();<br><br>  runApp(const MyApp());<br>}</pre><h3>Step 4: Clean Usage inside Repositories or Blocs</h3><p>Now that everything is cleanly wired up, your UI components or state managers (Bloc, Riverpod, Cubit) don’t need to know anything about FlutterSecureStorage. They simply request the abstraction.</p><p>Here is an example of an AuthRepository pulling the service seamlessly:</p><pre>class AuthRepository {<br>  // Pull the implementation abstractly via GetIt<br>  final SecureStorageService _secureStorage = locator&lt;SecureStorageService&gt;();<br><br>  Future&lt;void&gt; persistToken(String token) async {<br>    await _secureStorage.write(&#39;auth_token&#39;, token);<br>  }<br><br>  Future&lt;String?&gt; getToken() async {<br>    return await _secureStorage.read(&#39;auth_token&#39;);<br>  }<br><br>  Future&lt;void&gt; logout() async {<br>    await _secureStorage.delete(&#39;auth_token&#39;);<br>  }<br>}</pre><h3>Wrapping Up</h3><p>By decoupling flutter_secure_storage using an interface and registering it with GetIt, you change local data storage from a messy, platform-dependent variable into a predictable, highly cohesive, and easily testable service layer. Your future self—and your security auditors—will thank you.</p><p><em>Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e44c8f33889f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Flutter Basics to Clean Architecture: Building a Note App with Modern Flutter]]></title>
            <link>https://medium.com/@tungenwarkartick/building-a-cross-platform-note-app-with-flutter-a-step-by-step-guide-14f934c0f13c?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/14f934c0f13c</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 11:06:00 GMT</pubDate>
            <atom:updated>2026-07-03T12:10:59.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s fast-paced world, note-taking apps have become an essential tool for productivity. Whether you’re a student, professional, or just someone who likes to jot down ideas, having a reliable note-taking app can make a world of difference. In this blog, we’ll explore how to build a <strong>cross-platform note app</strong> using <strong>Flutter</strong>, a powerful UI toolkit by Google that allows you to create natively compiled applications for mobile, web, and desktop from a single codebase.</p><p>This blog will walk you through the architecture, key features, and implementation details of the <a href="https://github.com/karttiktungenwar/note_app">note_app</a> project. By the end, you’ll have a clear understanding of how to build your own note-taking app and deploy it across multiple platforms.</p><h3>Why Flutter?</h3><p>Flutter is an open-source framework that has gained immense popularity for its ability to create <strong>beautiful, natively compiled, multi-platform applications</strong> from a single codebase. Here’s why Flutter is a great choice for this project:</p><ul><li><strong>Single Codebase</strong>: Write once, run anywhere — iOS, Android, web, and desktop.</li><li><strong>Hot Reload</strong>: See changes in real-time without restarting the app.</li><li><strong>Rich Widget Library</strong>: Flutter provides a comprehensive set of widgets for building complex UIs.</li><li><strong>Performance</strong>: Compiled to native ARM code, ensuring high performance.</li><li><strong>Community Support</strong>: A large and active community for troubleshooting and learning.</li></ul><h3>Project Overview</h3><p>The <a href="https://github.com/karttiktungenwar/note_app">note_app</a> is a Flutter-based note-taking application designed to work seamlessly across <strong>Android, iOS, and the web</strong>. The repository structure is organized to support multi-platform development, with dedicated folders for each platform (android, ios, web) and a shared lib directory for the core Dart code.</p><h3>Repository Structure</h3><pre>note_app/<br>├── android/          # Android-specific code<br>├── ios/              # iOS-specific code<br>├── lib/              # Core Dart code (shared across platforms)<br>│   ├── scr/<br>│   │   ├── app/          # Dependency Injection (DI)<br>│   │   ├── core/         # Network , Database, Constants, Error and so on<br>│   │   ├── features/     # Bloc, Presentation, Widgets<br>│   └── main.dart     # Entry point<br>├── web/              # Web-specific code<br>├── test/             # Unit and widget tests<br>├── pubspec.yaml      # Dependencies and assets<br>└── README.md         # Project documentation</pre><h3>Key Features</h3><ol><li><strong>Cross-Platform Support</strong>: Works on Android, iOS, and the web.</li><li><strong>State Management</strong>: Uses <strong>Provider</strong> or <strong>Riverpod</strong> for efficient state management.</li><li><strong>Local Storage</strong>: Stores notes locally using <strong>Hive</strong> or <strong>SharedPreferences</strong>.</li><li><strong>Clean Architecture</strong>: Follows for maintainability.</li><li><strong>Error Handling</strong>: Robust error handling with custom classes (e.g., Failure class).</li></ol><h3>Step 1: Setting Up the Flutter Project</h3><h3>Prerequisites</h3><ul><li>Install <a href="https://flutter.dev/docs/get-started/install">Flutter SDK</a></li><li>Set up an IDE (e.g., <strong>Android Studio</strong>, <strong>VS Code</strong>)</li><li>Ensure you have the required dependencies (e.g., Dart, Flutter plugins)</li></ul><h3>Creating the Project</h3><p>Run the following command to create a new Flutter project:</p><pre>flutter create note_app<br>cd note_app</pre><h3>Adding Dependencies</h3><p>Update the pubspec.yaml file to include the necessary packages:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>    # The following adds the Cupertino Icons font to your application.<br>    # Use with the CupertinoIcons class for iOS style icons.<br>    cupertino_icons: ^1.0.8<br>    flutter_bloc: ^8.1.3<br>    equatable: ^2.0.5<br>    hive: ^2.2.3<br>    hive_flutter: ^1.1.0<br>    uuid: ^3.0.7<br>    get_it: ^7.6.4<br>    dartz: ^0.10.1</pre><h3>Step 2: Defining the Data Model</h3><p>The Note model represents the structure of a note in the app. Here’s a simple implementation:</p><pre>// lib/src/features/domain/entity/note.dart<br>class Note {<br>  final String id;<br>  final String title;<br>  final String content;<br>  final DateTime createdAt;<br><br>  Note({<br>    required this.id,<br>    required this.title,<br>    required this.content,<br>    required this.createdAt,<br>  });<br>}</pre><pre>// lib/src/features/data/model/note_model.dart<br>class NoteModel extends Note {<br>  NoteModel({<br>    required super.id,<br>    required super.title,<br>    required super.content,<br>    required super.createdAt,<br>  });<br><br>  factory NoteModel.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return NoteModel(<br>      id: json[&#39;id&#39;],<br>      title: json[&#39;title&#39;],<br>      content: json[&#39;content&#39;],<br>      createdAt: DateTime.parse(json[&#39;createdAt&#39;]),<br>    );<br>  }<br><br>  Map&lt;String, dynamic&gt; toJson() {<br>    return {<br>      &#39;id&#39;: id,<br>      &#39;title&#39;: title,<br>      &#39;content&#39;: content,<br>      &#39;createdAt&#39;: createdAt.toIso8601String(),<br>    };<br>  }<br><br>  Note toEntity() {<br>    return Note(<br>      id: id,<br>      title: title,<br>      content: content,<br>      createdAt: createdAt,<br>    );<br>  }<br>}</pre><h3>Step 3: Implementing Local Storage with Hive</h3><p>Hive is a lightweight and fast NoSQL database for Flutter. Here’s how to set it up:</p><h3>Initialize Hive</h3><p>Add the following to your app_database.dart:</p><pre>// lib/src/core/database/app_database.dart<br>abstract class AppDatabase {<br>  Box get appBox;<br>  Future&lt;void&gt; init();<br>}<br><br>class AppDatabaseImpl implements AppDatabase {<br>  final String hivePathSuffix;<br>  AppDatabaseImpl({required this.hivePathSuffix});<br>  late Box _appBox;<br>  @override<br>  Box get appBox =&gt; _appBox;<br>  @override<br>  Future&lt;void&gt; init() async {<br>    final directory = await getApplicationDocumentsDirectory();<br>    Hive.init(&#39;${directory.path}/$hivePathSuffix/hive&#39;);<br>    _appBox = await Hive.openBox(&#39;notemaker_$hivePathSuffix&#39;);<br>  }<br>}</pre><h3>Create a Note Service</h3><p>The NoteLocalDataSource class handles all CRUD operations for notes:</p><pre>// lib/src/features/data/data_source/note_local_data_source.dart&#39;;<br>abstract class NoteLocalDataSource {<br>  Future&lt;List&lt;NoteModel&gt;&gt; getNotes();<br>  Future&lt;void&gt; addNote(NoteModel note);<br>  Future&lt;void&gt; updateNote(NoteModel note);<br>  Future&lt;void&gt; deleteNote(String id);<br>}<br><br>class NoteLocalDataSourceImpl implements NoteLocalDataSource {<br>  final AppDatabase appDatabase;<br><br>  NoteLocalDataSourceImpl({required this.appDatabase});<br><br>  @override<br>  Future&lt;List&lt;NoteModel&gt;&gt; getNotes() async {<br>     final notes = appDatabase.appBox.values<br>            .map((e) =&gt; NoteModel.fromJson(Map&lt;String, dynamic&gt;.from(e as Map)))<br>            .toList();<br>        return notes.cast&lt;NoteModel&gt;();<br>  }<br><br>  @override<br>  Future&lt;void&gt; addNote(NoteModel note) async {<br>    await appDatabase.appBox.put(note.id, note.toJson());<br>  }<br><br>  @override<br>  Future&lt;void&gt; updateNote(NoteModel note) async {<br>    await appDatabase.appBox.put(note.id, note.toJson());<br>  }<br><br>  @override<br>  Future&lt;void&gt; deleteNote(String id) async {<br>    await appDatabase.appBox.delete(id);<br>  }<br>}</pre><h3>Step 4: Building the Handle Error and Constants</h3><pre>// lib/src/core/error/failure.dart<br>abstract class Failure {<br>  final String message;<br><br>  const Failure({required this.message});<br><br>   @override<br>  String toString() =&gt; message;<br>}<br><br>class CacheFailure extends Failure {<br>  const CacheFailure({required super.message});<br>}<br><br>class NoDataFailure extends Failure {<br>  const NoDataFailure({required super.message})<br>}</pre><pre>// lib/src/src/core/constants/app_constants.dart<br>abstract class AppConstants {<br>  static const String hiveBoxName = &#39;notes&#39;;<br>}</pre><h3>Step 5: Building the Repository</h3><pre>// lib/src/features/domain/repository/note_repository.dart<br>abstract class NoteRepository {<br>  Future&lt;Either&lt;Failure, List&lt;Note&gt;&gt;&gt; getNotes();<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; addNote(Note note);<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; updateNote(Note note);<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; deleteNote(String id);<br>  Future&lt;Either&lt;Failure, List&lt;Note&gt;&gt;&gt; getSearchNotes(String query);<br>}</pre><pre>// lib/src/features/data/repository/note_repository.dart<br>class NoteRepositoryImpl implements NoteRepository {<br>  final NoteLocalDataSource localDataSource;<br><br>  NoteRepositoryImpl({required this.localDataSource});<br><br>  @override<br>  Future&lt;Either&lt;Failure, List&lt;Note&gt;&gt;&gt; getNotes() async {<br>    try {<br>      final models = await localDataSource.getNotes();<br><br>      if (models.isEmpty) {<br>        return Left(<br>            NoDataFailure(message: &#39;No notes found&#39;)<br>        );<br>      }<br><br>      return Right(<br>        models.map((e) =&gt; e.toEntity()).toList(),<br>      );<br>    }catch (e) {<br>      return Left(<br>        CacheFailure(message: e.toString()),<br>      );<br>    }<br><br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; addNote(Note note) async {<br>    try {<br>      await localDataSource.addNote(<br>        NoteModel(<br>          id: note.id,<br>          title: note.title,<br>          content: note.content,<br>          createdAt: note.createdAt,<br>        ),<br>      );<br><br>      return Right(unit);<br>    } catch (e) {<br>      return Left(<br>        CacheFailure(message: e.toString()),<br>      );<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; updateNote(Note note) async {<br>    try {<br>      await localDataSource.updateNote(<br>        NoteModel(<br>          id: note.id,<br>          title: note.title,<br>          content: note.content,<br>          createdAt: note.createdAt,<br>        ),<br>      );<br><br>      return Right(unit);<br>    } catch (e) {<br>      return Left(<br>        CacheFailure(message: e.toString()),<br>      );<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; deleteNote(String id) async {<br>    try {<br>      await localDataSource.deleteNote(id);<br>      return Right(unit);<br>    } catch (e) {<br>      return Left(<br>        CacheFailure(message: e.toString()),<br>      );<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, List&lt;Note&gt;&gt;&gt; getSearchNotes(String query) async{<br>    try {<br>      final models = await localDataSource.getNotes();<br><br>      if (models.isEmpty) {<br>        return Left(<br>            NoDataFailure(message: &#39;No notes found&#39;)<br>        );<br>      }<br><br>      final filtered = models.where((note) {<br>        final title = note.title.toLowerCase();<br>        final content = note.content.toLowerCase();<br>        final q = query.toLowerCase();<br><br>        return title.contains(q) || content.contains(q);<br>      }).toList();<br><br>      if (filtered.isEmpty) {<br>        return Left(<br>          NoDataFailure(message: &#39;No matching notes found&#39;),<br>        );<br>      }<br><br>      return Right(filtered.map((e) =&gt; e.toEntity()).toList());<br>    } catch (e) {<br>      return Left(<br>        CacheFailure(message: e.toString()),<br>      );<br>    }<br>  }<br><br>}</pre><h3>Step 6: Building the UI</h3><p>Add Bloc first</p><pre>// lib/src/features/presentation/bloc/note_bloc.dart<br>part &#39;note_event.dart&#39;;<br>part &#39;note_state.dart&#39;;<br><br>class NoteBloc extends Bloc&lt;NoteEvent, NoteState&gt; {<br>  final AddNoteUsecase addNote;<br>  final DeleteNoteUsecase deleteNote;<br>  final GetNotesUsecase getNotes;<br>  final UpdateNoteUsecase updateNote;<br>  final SearchNoteUsecase searchNote;<br><br>  NoteBloc({<br>    required this.addNote,<br>    required this.deleteNote,<br>    required this.getNotes,<br>    required this.updateNote,<br>    required this.searchNote<br>  }) : super(NoteInitial()) {<br>    on&lt;LoadNotes&gt;(_onLoadNotes);<br>    on&lt;AddNewNote&gt;(_onAddNote);<br>    on&lt;UpdateExistingNote&gt;(_onUpdateNote);<br>    on&lt;DeleteExistingNote&gt;(_onDeleteNote);<br>    on&lt;SearchNotes&gt;(_onSearchNotes);<br>  }<br><br>  Future&lt;void&gt; _onLoadNotes(<br>      LoadNotes event,<br>      Emitter&lt;NoteState&gt; emit,<br>      ) async {<br>    emit(NoteLoading());<br><br>    final result = await getNotes();<br><br>    result.fold(<br>          (failure) =&gt; emit(NoteError(failure.message)),<br>          (notes) =&gt; emit(NoteLoaded(notes: notes)),<br>    );<br>  }<br><br>  Future&lt;void&gt; _onSearchNotes(<br>      SearchNotes event,<br>      Emitter&lt;NoteState&gt; emit,<br>      ) async {<br>    emit(NoteLoading());<br><br>    final result = await searchNote(event.query);<br><br>    result.fold(<br>          (failure) =&gt; emit(NoteError(failure.message)),<br>          (notes) =&gt; emit(NoteLoaded(notes: notes)),<br>    );<br>  }<br><br>  Future&lt;void&gt; _onAddNote(<br>      AddNewNote event,<br>      Emitter&lt;NoteState&gt; emit,<br>      ) async {<br>    final result = await addNote(event.note);<br><br>    result.fold(<br>          (failure) =&gt; emit(NoteError(failure.message)),<br>          (_) =&gt; add(LoadNotes()),<br>    );<br>  }<br><br>  Future&lt;void&gt; _onUpdateNote(<br>      UpdateExistingNote event,<br>      Emitter&lt;NoteState&gt; emit,<br>      ) async {<br>    final result = await updateNote(event.note);<br><br>    result.fold(<br>          (failure) =&gt; emit(NoteError(failure.message)),<br>          (_) =&gt; add(LoadNotes()),<br>    );<br>  }<br><br>  Future&lt;void&gt; _onDeleteNote(<br>      DeleteExistingNote event,<br>      Emitter&lt;NoteState&gt; emit,<br>      ) async {<br>    final result = await deleteNote(event.id);<br><br>    result.fold(<br>          (failure) =&gt; emit(NoteError(failure.message)),<br>          (_) =&gt; add(LoadNotes()),<br>    );<br>  }<br>}</pre><pre>// lib/src/features/presentation/bloc/note_event.dart<br>part of &#39;note_bloc.dart&#39;;<br><br>sealed class NoteEvent{<br>  const NoteEvent();<br>}<br><br>class LoadNotes extends NoteEvent {}<br><br>class AddNewNote extends NoteEvent {<br>  final Note note;<br><br>  const AddNewNote(this.note);<br>}<br><br>class UpdateExistingNote extends NoteEvent {<br>  final Note note;<br><br>  const UpdateExistingNote(this.note);<br>}<br><br>class DeleteExistingNote extends NoteEvent {<br>  final String id;<br><br>  const DeleteExistingNote(this.id);<br><br>}<br><br>class SearchNotes extends NoteEvent{<br>  final String query;<br><br>  const SearchNotes(this.query);<br>}</pre><pre>// lib/src/features/presentation/bloc/note_state.dart<br>part of &#39;note_bloc.dart&#39;;<br><br>abstract class NoteState extends Equatable {<br>  const NoteState();<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class NoteInitial extends NoteState {}<br><br>class NoteLoading extends NoteState {}<br><br>class NoteLoaded extends NoteState {<br>  final List&lt;Note&gt; notes;<br><br>  const NoteLoaded({required this.notes});<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [notes];<br>}<br><br>class NoteError extends NoteState {<br>  final String message;<br><br>  const NoteError(this.message);<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [message];<br>}</pre><p>Add Screen</p><pre>// lib/src/features/presentation/screens/notes_page.dart<br>class NotesPage extends StatefulWidget {<br>  const NotesPage({super.key});<br><br>  @override<br>  State&lt;NotesPage&gt; createState() =&gt; _NotesPageState();<br>}<br><br>class _NotesPageState extends State&lt;NotesPage&gt; {<br>  final ValueNotifier&lt;bool&gt; _isSearching = ValueNotifier(false);<br>  final TextEditingController _searchController = TextEditingController();<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    WidgetsBinding.instance.addPostFrameCallback((_) {<br>      context.read&lt;NoteBloc&gt;().add(LoadNotes());<br>    });<br><br>    _searchController.addListener(() {<br>      final query = _searchController.text.trim();<br>      context.read&lt;NoteBloc&gt;().add(SearchNotes(query));<br>    });<br>  }<br><br>  @override<br>  void dispose() {<br>    _isSearching.dispose();<br>    _searchController.dispose();<br>    super.dispose();<br>  }<br><br>  PreferredSizeWidget _buildAppBar() {<br>    return AppBar(<br>      title: ValueListenableBuilder&lt;bool&gt;(<br>        valueListenable: _isSearching,<br>        builder: (context, searching, _) {<br>          if (!searching) return const Text(&#39;Notes&#39;);<br><br>          return TextField(<br>            controller: _searchController,<br>            autofocus: true,<br>            decoration: InputDecoration(<br>              hintText: &#39;Search notes...&#39;,<br>              hintStyle: const TextStyle(color: Colors.grey),<br>              filled: true,<br>              fillColor: Colors.grey.shade200,<br>              border: OutlineInputBorder(<br>                borderRadius: BorderRadius.circular(16),<br>                borderSide: BorderSide.none,<br>              ),<br>              enabledBorder: OutlineInputBorder(<br>                borderRadius: BorderRadius.circular(16),<br>                borderSide: const BorderSide(color: Colors.grey),<br>              ),<br>              focusedBorder: OutlineInputBorder(<br>                borderRadius: BorderRadius.circular(16),<br>                borderSide: const BorderSide(color: Colors.grey, width: 1.5),<br>              ),<br>              contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),<br>            ),<br>            style: const TextStyle(color: Colors.black),<br>            onChanged: (value) {<br>              context.read&lt;NoteBloc&gt;().add(SearchNotes(value.trim()));<br>            },<br>          );<br>        },<br>      ),<br>      actions: [<br>        ValueListenableBuilder&lt;bool&gt;(<br>          valueListenable: _isSearching,<br>          builder: (context, searching, _) {<br>            return IconButton(<br>              icon: Icon(searching ? Icons.close : Icons.search),<br>              onPressed: () {<br>                if (searching) {<br>                  _searchController.clear();<br>                  context.read&lt;NoteBloc&gt;().add(SearchNotes(&#39;&#39;));<br>                }<br>                _isSearching.value = !searching;<br>              },<br>            );<br>          },<br>        ),<br>      ],<br>    );<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: _buildAppBar(),<br>      body: BlocBuilder&lt;NoteBloc, NoteState&gt;(<br>        builder: (context, state) {<br>          if (state is NoteLoading) {<br>            return const Center(child: CircularProgressIndicator());<br>          }<br><br>          if (state is NoteLoaded) {<br>            return NoteList(notes: state.notes);<br>          }<br><br>          if (state is NoteError) {<br>            return Center(child: Text(state.message));<br>          }<br><br>          return const Center(child: Text(&#39;No notes found&#39;));<br>        },<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () =&gt; Navigator.push(<br>          context,<br>          MaterialPageRoute(builder: (_) =&gt; const NoteForm()),<br>        ),<br>        child: const Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><p>Add Widgets</p><pre>// lib/src/features/presentation/widgets/note_form.dart<br>class NoteForm extends StatefulWidget {<br>  final Note? note;<br><br>  const NoteForm({super.key, this.note});<br><br>  @override<br>  State&lt;NoteForm&gt; createState() =&gt; _NoteFormState();<br>}<br><br>class _NoteFormState extends State&lt;NoteForm&gt; {<br>  final _formKey = GlobalKey&lt;FormState&gt;();<br>  late String _title;<br>  late String _content;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _title = widget.note?.title ?? &#39;&#39;;<br>    _content = widget.note?.content ?? &#39;&#39;;<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Add/Edit Note&#39;)),<br>      body: Padding(<br>        padding: const EdgeInsets.all(16.0),<br>        child: Form(<br>          key: _formKey,<br>          child: Column(<br>            children: [<br>              TextFormField(<br>                initialValue: _title,<br>                decoration: const InputDecoration(labelText: &#39;Title&#39;),<br>                validator: (value) =&gt; value?.isEmpty ?? true ? &#39;Required&#39; : null,<br>                onSaved: (value) =&gt; _title = value!,<br>              ),<br>              TextFormField(<br>                initialValue: _content,<br>                decoration: const InputDecoration(labelText: &#39;Content&#39;),<br>                validator: (value) =&gt; value?.isEmpty ?? true ? &#39;Required&#39; : null,<br>                onSaved: (value) =&gt; _content = value!,<br>              ),<br>              const SizedBox(height: 20),<br>              ElevatedButton(<br>                onPressed: () {<br>                  if (_formKey.currentState!.validate()) {<br>                    _formKey.currentState!.save();<br>                    final note = Note(<br>                      id: widget.note?.id ?? const Uuid().v4(),<br>                      title: _title,<br>                      content: _content,<br>                      createdAt: widget.note?.createdAt ?? DateTime.now(),<br>                    );<br>                    if (widget.note == null) {<br>                      BlocProvider.of&lt;NoteBloc&gt;(context).add(AddNewNote(note));<br>                    } else {<br>                      BlocProvider.of&lt;NoteBloc&gt;(context).add(UpdateExistingNote(note));<br>                    }<br>                    Navigator.pop(context);<br>                  }<br>                },<br>                child: const Text(&#39;Save&#39;),<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><pre>// lib/src/features/presentation/widgets/note_item.dart<br>class NoteItem extends StatelessWidget {<br>  final Note note;<br><br>  const NoteItem({super.key, required this.note});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Card(<br>      child: ListTile(<br>        title: Text(note.title),<br>        subtitle: Text(note.content),<br>        trailing: IconButton(<br>          icon: const Icon(Icons.delete),<br>          onPressed: () =&gt; BlocProvider.of&lt;NoteBloc&gt;(context).add(DeleteExistingNote(note.id)),<br>        ),<br>        onTap: () =&gt; Navigator.push(<br>          context,<br>          MaterialPageRoute(builder: (_) =&gt; NoteForm(note: note)),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><pre>// lib/src/features/presentation/widgets/note_list.dart<br>class NoteList extends StatelessWidget {<br>  final List&lt;Note&gt; notes;<br><br>  const NoteList({super.key, required this.notes});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ListView.builder(<br>      itemCount: notes.length,<br>      itemBuilder: (context, index) =&gt; NoteItem(note: notes[index]),<br>    );<br>  }<br>}</pre><p>Flutter main</p><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await init();<br>  runApp(const NoteApp());<br>}<br><br>class NoteApp extends StatelessWidget {<br>  const NoteApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MultiBlocProvider(<br>      providers: [<br>        BlocProvider(create: (_) =&gt; di.sl&lt;NoteBloc&gt;()),<br>      ],<br>      child: MaterialApp(<br>        title: &#39;Note App&#39;,<br>        theme: ThemeData(primarySwatch: Colors.blue),<br>        home: const NotesPage(),<br>      ),<br>    );<br>  }<br><br><br>}</pre><h3>Step 7: Building the DI</h3><pre>// lib/src/app/di/injection_container.dart<br>final sl = GetIt.instance;<br><br>Future&lt;void&gt; init() async {<br><br>  // Bloc<br>  sl.registerFactory(() =&gt; NoteBloc(<br>    addNote: sl(),<br>    deleteNote: sl(),<br>    getNotes: sl(),<br>    updateNote: sl(),<br>    searchNote: sl(),<br>  ));<br><br>  // AppDatabase<br>  sl.registerLazySingleton&lt;AppDatabase&gt;(<br>        () =&gt; AppDatabaseImpl(hivePathSuffix: AppConstants.hiveBoxName),<br>  );<br>  await sl&lt;AppDatabase&gt;().init();<br><br>  // Use cases<br>  sl.registerLazySingleton(() =&gt; AddNoteUsecase(sl()));<br>  sl.registerLazySingleton(() =&gt; DeleteNoteUsecase(sl()));<br>  sl.registerLazySingleton(() =&gt; GetNotesUsecase(sl()));<br>  sl.registerLazySingleton(() =&gt; UpdateNoteUsecase(sl()));<br>  sl.registerLazySingleton(() =&gt; SearchNoteUsecase(sl()));<br><br>  // Repository<br>  sl.registerLazySingleton&lt;NoteRepository&gt;(<br>          () =&gt; NoteRepositoryImpl(localDataSource: sl()));<br><br>  // Data sources<br>  sl.registerLazySingleton&lt;NoteLocalDataSource&gt;(<br>          () =&gt; NoteLocalDataSourceImpl(appDatabase: sl&lt;AppDatabase&gt;()));<br>}</pre><h3>Step 8: Deploying the App</h3><h3>Android</h3><ol><li>Run flutter build apk to generate an APK.</li><li>Distribute the APK via the Google Play Store or directly to users.</li></ol><h3>iOS</h3><ol><li>Run flutter build ios to build the iOS app.</li><li>Open the project in Xcode and archive it for distribution via the App Store.</li></ol><h3>Web</h3><ol><li>Run flutter build web to generate a production-ready web app.</li><li>Deploy the build/web folder to a web server (e.g., Firebase Hosting, Netlify, or GitHub Pages).</li></ol><h3>Conclusion</h3><p>Building a cross-platform note app with Flutter is a rewarding experience. Flutter’s flexibility, performance, and extensive widget library make it an excellent choice for developing apps that work seamlessly across multiple platforms. The <a href="https://github.com/karttiktungenwar/note_app">note_app</a> project demonstrates how to structure a Flutter app for maintainability, scalability, and cross-platform compatibility.</p><p>By following the steps outlined in this blog, you can create your own note-taking app and customize it to fit your needs. Whether you’re a beginner or an experienced developer, Flutter provides the tools you need to bring your ideas to life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14f934c0f13c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Story: Mastering ListView with Expanded]]></title>
            <link>https://medium.com/@tungenwarkartick/flutter-story-mastering-listview-with-expanded-141804ba3367?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/141804ba3367</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 09:39:28 GMT</pubDate>
            <atom:updated>2026-04-22T09:39:28.059Z</atom:updated>
            <content:encoded><![CDATA[<h3>📖 Summary</h3><p>A practical journey through Flutter’s ListView widget, exploring how to combine it with Expanded for dynamic, scrollable content in constrained layouts. Perfect for beginners to intermediate developers building responsive UIs with lists inside Columns, Rows, or complex layouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PlimUx-KodaDAgRiSCa8g.jpeg" /></figure><h3>The Challenge: ListView with Expanded</h3><p>1.StatefulWidget</p><pre>class FaqCategoryListingScreen extends StatefulWidget {<br>  final String categoryName;<br>  const FaqCategoryListingScreen({super.key, required this.categoryName});<br><br>  @override<br>  State&lt;FaqCategoryListingScreen&gt; createState() =&gt; _FaqCategoryListingScreenState();<br>}<br><br>class _FaqCategoryListingScreenState extends State&lt;FaqCategoryListingScreen&gt; {<br>  final OverlayPortalController _overlayPortalController = OverlayPortalController();<br>  final ValueNotifier&lt;List&lt;FAQCategoryListingDataModel&gt;&gt; lists = ValueNotifier([]);<br>  final ValueNotifier&lt;List&lt;bool&gt;&gt; _isExpandedListNotifier = ValueNotifier([]);<br>  <br>  // Edit dialog controllers<br>  final TextEditingController _questionController = TextEditingController();<br>  final TextEditingController _answerController = TextEditingController();<br>  int? _editingIndex;<br><br>  @override<br>  void dispose() {<br>    lists.dispose();<br>    _isExpandedListNotifier.dispose();<br>    _questionController.dispose();<br>    _answerController.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  void initState() {<br>    lists.value = [<br>      FAQCategoryListingDataModel(<br>        question: &quot;Application is taking a lot of time to download&quot;,<br>        answer: &quot;Download speed of the application will depend on the internet speed availability on your device. Kindly check your internet connection. You will be able to obtain exact information on the download progress from your device notification pane.&quot;,<br>      ),<br>      FAQCategoryListingDataModel(<br>        question: &quot;I am unable to install the application on my device&quot;,<br>        answer: &quot;Please check if sufficient space is available in your device memory. If you have installed any security applications on your device, kindly disable them and retry installing the application.&quot;,<br>      ),<br>      FAQCategoryListingDataModel(<br>        question: &quot;I enter my ETOP number and click on Generate OTP but keep seeing a loading / processing circle.&quot;,<br>        answer: &quot;Application requires internet connection in order to verify the OTP you provide. Please check the internet connection on the device.&quot;,<br>      ),<br>      FAQCategoryListingDataModel(<br>        question: &quot;I enter my ETOP number but keep receiving a pop-up ETOP number verification failed&quot;,<br>        answer: &quot;This pop-up will be displayed if the number entered by you does not match with that saved in the system. Kindly check the number that you have entered. Application requires that your ETOP number should be registered in the system before you go ahead with the registration. If the problem persists, please contact the DHL at 129/50129.&quot;,<br>      ),<br>      FAQCategoryListingDataModel(<br>        question: &quot;Application says OTP has been sent to your mobile number but I do not receive the OTP on my phone.&quot;,<br>        answer: &quot;Application will send the OTP to your registered ETOP number. Please check the phone which contains the SIM bearing the registered ETOP number. If you are using the correct phone and still do not receive the SMS, try clicking the Resend OTP link. Application will resend the OTP to your registered ETOP number.&quot;,<br>      ),<br>    ];<br>    _isExpandedListNotifier.value = List.generate(lists.value.length, (index) =&gt; false);<br>    super.initState();<br>  }<br><br>  /// Show edit dialog for FAQ item<br>  void _showEditDialog(int index) {<br>    final faqItem = lists.value[index];<br>    _editingIndex = index;<br>    <br>    _questionController.text = faqItem.question;<br>    _answerController.text = faqItem.answer;<br><br>    showDialog(<br>      context: context,<br>      barrierDismissible: false,<br>      builder: (BuildContext context) {<br>        return StatefulBuilder(<br>          builder: (context, setDialogState) {<br>            return AlertDialog(<br>              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),<br>              title: Row(<br>                children: [<br>                  Icon(Icons.edit, color: Colors.orange[700], size: 24),<br>                  const SizedBox(width: 12),<br>                  Text(<br>                    &#39;Edit FAQ&#39;,<br>                    style: TextStyle(<br>                      fontWeight: FontWeight.bold,<br>                      color: Colors.orange[800],<br>                    ),<br>                  ),<br>                ],<br>              ),<br>              content: SingleChildScrollView(<br>                child: Column(<br>                  mainAxisSize: MainAxisSize.min,<br>                  crossAxisAlignment: CrossAxisAlignment.start,<br>                  children: [<br>                    TextField(<br>                      controller: _questionController,<br>                      maxLines: 2,<br>                      decoration: InputDecoration(<br>                        labelText: &#39;Question&#39;,<br>                        border: OutlineInputBorder(<br>                          borderRadius: BorderRadius.circular(12),<br>                        ),<br>                        focusedBorder: OutlineInputBorder(<br>                          borderRadius: BorderRadius.circular(12),<br>                          borderSide: BorderSide(color: Colors.orange[400]!, width: 2),<br>                        ),<br>                      ),<br>                    ),<br>                    const SizedBox(height: 16),<br>                    TextField(<br>                      controller: _answerController,<br>                      maxLines: 4,<br>                      decoration: InputDecoration(<br>                        labelText: &#39;Answer&#39;,<br>                        border: OutlineInputBorder(<br>                          borderRadius: BorderRadius.circular(12),<br>                        ),<br>                        focusedBorder: OutlineInputBorder(<br>                          borderRadius: BorderRadius.circular(12),<br>                          borderSide: BorderSide(color: Colors.orange[400]!, width: 2),<br>                        ),<br>                      ),<br>                    ),<br>                  ],<br>                ),<br>              ),<br>              actions: [<br>                TextButton(<br>                  onPressed: () =&gt; Navigator.of(context).pop(),<br>                  child: const Text(&#39;Cancel&#39;, style: TextStyle(color: Colors.grey)),<br>                ),<br>                ElevatedButton(<br>                  onPressed: () {<br>                    _updateFAQItem();<br>                    Navigator.of(context).pop();<br>                  },<br>                  style: ElevatedButton.styleFrom(<br>                    backgroundColor: Colors.orange[600],<br>                    foregroundColor: Colors.white,<br>                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),<br>                  ),<br>                  child: const Text(&#39;Update&#39;),<br>                ),<br>              ],<br>            );<br>          },<br>        );<br>      },<br>    );<br>  }<br><br>  /// Update FAQ item at specific index<br>  void _updateFAQItem() {<br>    if (_editingIndex != null &amp;&amp; <br>        _questionController.text.trim().isNotEmpty &amp;&amp; <br>        _answerController.text.trim().isNotEmpty) {<br>      <br>      final updatedList = List&lt;FAQCategoryListingDataModel&gt;.from(lists.value);<br>      updatedList[_editingIndex!] = FAQCategoryListingDataModel(<br>        question: _questionController.text.trim(),<br>        answer: _answerController.text.trim(),<br>      );<br>      <br>      lists.value = updatedList;<br>      <br>      // Update expansion state list if needed<br>      final updatedExpansionList = List&lt;bool&gt;.from(_isExpandedListNotifier.value);<br>      if (_editingIndex! &gt;= updatedExpansionList.length) {<br>        updatedExpansionList.add(false);<br>      }<br>      _isExpandedListNotifier.value = updatedExpansionList;<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (_) =&gt; s1&lt;HelpAndSupportBloc&gt;(),<br>      child: Scaffold(<br>        appBar: CustomImageAppBar(<br>          title: &#39;FAQ&#39;,<br>          imageUrl: AppAssets.appbarBackground,<br>          showBackButton: false,<br>        ),<br>        body: MultiBlocListener(<br>          listeners: [<br>            BlocListener&lt;HelpAndSupportBloc, HelpAndSupportState&gt;(<br>              listener: (context, state) {},<br>            ),<br>          ],<br>          child: OverlayPortal(<br>            controller: _overlayPortalController,<br>            overlayChildBuilder: (context) =&gt; const Center(<br>              child: CircularProgressIndicator(),<br>            ),<br>            child: ValueListenableBuilder&lt;List&lt;bool&gt;&gt;(<br>              valueListenable: _isExpandedListNotifier,<br>              builder: (context, isExpandedList, child) {<br>                return ListView.builder(<br>                  itemCount: lists.value.length,<br>                  itemBuilder: (context, index) {<br>                    return Container(<br>                      margin: const EdgeInsets.all(8.0),<br>                      decoration: BoxDecoration(<br>                        color: Colors.orange[50],<br>                        borderRadius: BorderRadius.circular(12.0),<br>                        border: Border.all(color: Colors.orange[200]!),<br>                        boxShadow: [<br>                          BoxShadow(<br>                            color: Colors.orange.withOpacity(0.1),<br>                            blurRadius: 8,<br>                            offset: const Offset(0, 2),<br>                          ),<br>                        ],<br>                      ),<br>                      child: Theme(<br>                        data: Theme.of(context).copyWith(dividerColor: Colors.transparent),<br>                        child: ExpansionTile(<br>                          leading: Icon(Icons.help_outline, color: Colors.orange[700]),<br>                          title: Text(<br>                            lists.value[index].question,<br>                            style: const TextStyle(<br>                              fontWeight: FontWeight.bold,<br>                              fontSize: 16,<br>                            ),<br>                          ),<br>                          trailing: Row(<br>                            mainAxisSize: MainAxisSize.min,<br>                            children: [<br>                              // Edit Button<br>                              IconButton(<br>                                onPressed: () =&gt; _showEditDialog(index),<br>                                icon: Icon(<br>                                  Icons.edit,<br>                                  color: Colors.orange[700],<br>                                  size: 20,<br>                                ),<br>                                tooltip: &#39;Edit FAQ&#39;,<br>                                padding: EdgeInsets.zero,<br>                                constraints: const BoxConstraints(minWidth: 32, minHeight: 32),<br>                                style: IconButton.styleFrom(<br>                                  backgroundColor: Colors.white.withOpacity(0.8),<br>                                  shape: RoundedRectangleBorder(<br>                                    borderRadius: BorderRadius.circular(8),<br>                                  ),<br>                                ),<br>                              ),<br>                              const SizedBox(width: 8),<br>                              // Expansion Icon<br>                              isExpandedList[index]<br>                                  ? const Icon(Icons.arrow_drop_up, color: Colors.orange)<br>                                  : const Icon(Icons.arrow_drop_down, color: Colors.orange),<br>                            ],<br>                          ),<br>                          onExpansionChanged: (isExpanded) {<br>                            final updatedList = List&lt;bool&gt;.from(isExpandedList);<br>                            updatedList[index] = isExpanded;<br>                            _isExpandedListNotifier.value = updatedList;<br>                          },<br>                          children: [<br>                            Container(<br>                              decoration: BoxDecoration(<br>                                color: Colors.white,<br>                                borderRadius: const BorderRadius.only(<br>                                  bottomLeft: Radius.circular(12),<br>                                  bottomRight: Radius.circular(12),<br>                                ),<br>                              ),<br>                              child: Padding(<br>                                padding: const EdgeInsets.all(16.0),<br>                                child: Text(<br>                                  lists.value[index].answer,<br>                                  style: TextStyle(<br>                                    color: Colors.grey[800],<br>                                    height: 1.5,<br>                                  ),<br>                                ),<br>                              ),<br>                            ),<br>                          ],<br>                        ),<br>                      ),<br>                    );<br>                  },<br>                );<br>              },<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>2. Model Class</p><pre>class FAQCategoryListingDataModel {<br>  final String question;<br>  final String answer;<br><br>  const FAQCategoryListingDataModel({required this.question, required this.answer});<br>}</pre><h3>🎯 Key Features Added:</h3><h3>1. Edit Button</h3><ul><li>Positioned next to expansion icon in trailing</li><li>Beautiful tooltip and styling</li><li>Compact design with hover effects</li></ul><h3>2. Professional Edit Dialog</h3><ul><li>StatefulBuilder for real-time UI updates</li><li>Two text fields (Question &amp; Answer) with proper styling</li><li>Input validation</li><li>Orange-themed design matching your app</li></ul><h3>3. Smooth Data Updates</h3><ul><li>Updates ValueNotifier lists instantly</li><li>Maintains expansion states</li><li>Handles edge cases (empty lists)</li></ul><h3>4. Enhanced UI/UX</h3><ul><li>Leading help icon for each FAQ</li><li>Box shadows for depth</li><li>Better answer container styling</li><li>Professional dialog design</li><li>Input validation &amp; focus states</li><li>Responsive padding &amp; spacing</li></ul><p>5. <strong>Production-Ready Code</strong></p><h3>🚀 How to Use:</h3><ol><li>Tap Edit Icon → Opens edit dialog</li><li>Modify Question/Answer → Real-time preview</li><li>Tap Update → Instantly reflects in ListView</li><li>Expansion State Preserved → Seamless UX</li></ol><p>Perfect for Admin panels, Content Management, or FAQ maintenance! ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141804ba3367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Beautiful QR Codes in Flutter: Generate & Share with Custom Styling]]></title>
            <link>https://medium.com/@tungenwarkartick/creating-beautiful-qr-codes-in-flutter-generate-share-with-custom-styling-e3f7197c734c?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f7197c734c</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 16:38:05 GMT</pubDate>
            <atom:updated>2026-04-17T16:38:05.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLp1caVUkMiROoCKocbxnw.png" /></figure><p>QR codes have become essential in modern apps for sharing links, contact info, payments, and more. In this tutorial, we’ll build a production-ready QR code generator with custom styling, embedded logos, and seamless sharing functionality.</p><h3>🎨 Complete Implementation</h3><h3>1. Dependencies</h3><p>Add these to your pubspec.yaml:</p><pre>dependencies:<br>  qr_flutter: ^4.1.0<br>  share_plus: ^7.2.2<br>  flutter:<br>    sdk: flutter</pre><p>2. The Complete QR Generator Widget</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:qr_flutter/qr_flutter.dart&#39;;<br>import &#39;package:share_plus/share_plus.dart&#39;;<br>import &#39;dart:typed_data&#39;;<br>import &#39;dart:ui&#39; as ui;<br><br>class QRGeneratorScreen extends StatefulWidget {<br>  @override<br>  _QRGeneratorScreenState createState() =&gt; _QRGeneratorScreenState();<br>}<br><br>class _QRGeneratorScreenState extends State&lt;QRGeneratorScreen&gt; {<br>  final ValueNotifier&lt;String&gt; qrDataNotifier = ValueNotifier&lt;String&gt;(&#39;&#39;);<br>  <br>  @override<br>  void dispose() {<br>    qrDataNotifier.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final size = MediaQuery.of(context).size.width * 0.7;<br>    <br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;QR Generator&#39;)),<br>      body: Padding(<br>        padding: EdgeInsets.all(24),<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            // QR Code Display<br>            ValueListenableBuilder&lt;String&gt;(<br>              valueListenable: qrDataNotifier,<br>              builder: (context, qrData, child) {<br>                return Container(<br>                  padding: EdgeInsets.all(24),<br>                  decoration: BoxDecoration(<br>                    color: Colors.white,<br>                    borderRadius: BorderRadius.circular(20),<br>                    boxShadow: [<br>                      BoxShadow(<br>                        color: Colors.black26,<br>                        blurRadius: 20,<br>                        offset: Offset(0, 10),<br>                      ),<br>                    ],<br>                  ),<br>                  child: QrImageView(<br>                    data: qrData.isEmpty ? &#39;Enter some text&#39; : qrData,<br>                    size: size,<br>                    backgroundColor: Colors.white,<br>                    eyeStyle: QrEyeStyle(<br>                      eyeShape: QrEyeShape.square,<br>                      color: Colors.blue.shade600,<br>                    ),<br>                    dataModuleStyle: QrDataModuleStyle(<br>                      dataModuleShape: QrDataModuleShape.square,<br>                      color: Colors.blue.shade600,<br>                    ),<br>                    embeddedImage: AssetImage(&#39;assets/logo.png&#39;), // Your logo<br>                    embeddedImageStyle: QrEmbeddedImageStyle(<br>                      size: Size.square(60),<br>                    ),<br>                  ),<br>                );<br>              },<br>            ),<br>            <br>            SizedBox(height: 32),<br>            <br>            // Input Field<br>            TextField(<br>              onChanged: (value) =&gt; qrDataNotifier.value = value,<br>              decoration: InputDecoration(<br>                labelText: &#39;Enter QR Data&#39;,<br>                border: OutlineInputBorder(),<br>                prefixIcon: Icon(Icons.link),<br>              ),<br>            ),<br>            <br>            SizedBox(height: 24),<br>            <br>            // Share Button<br>            TextButton.icon(<br>              onPressed: () {<br>                ContextExtension(context).shareQRCode(<br>                  data: qrDataNotifier.value,<br>                  description: &#39;Scan this QR code to visit our site! 🚀&#39;,<br>                  logoAssetPath: &#39;assets/logo.png&#39;,<br>                );<br>              },<br>              icon: Icon(Icons.share, size: 20),<br>              label: Text(&#39;Share QR Code&#39;, style: TextStyle(fontSize: 18)),<br>              style: TextButton.styleFrom(<br>                backgroundColor: Colors.blue.shade600,<br>                foregroundColor: Colors.white,<br>                padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16),<br>                shape: RoundedRectangleBorder(<br>                  borderRadius: BorderRadius.circular(12),<br>                ),<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>3. 🔥 The Magic Sharing Extension</p><pre>extension ContextExtension on BuildContext {<br>  Future&lt;void&gt; shareQRCode({<br>    required String data,<br>    String description = &quot;Scan this QR code&quot;,<br>    String? logoAssetPath,<br>  }) async {<br>    try {<br>      // Load logo as ui.Image (null-safe)<br>      final ui.Image? logoImage = logoAssetPath != null<br>          ? await _loadUiImage(logoAssetPath)<br>          : null;<br><br>      // Create beautifully styled QR Painter<br>      final qrPainter = QrPainter(<br>        data: data,<br>        version: QrVersions.auto,<br>        eyeStyle: QrEyeStyle(<br>          eyeShape: QrEyeShape.square,<br>          color: Colors.blue.shade600,<br>        ),<br>        dataModuleStyle: QrDataModuleStyle(<br>          dataModuleShape: QrDataModuleShape.square,<br>          color: Colors.blue.shade600,<br>        ),<br>        embeddedImage: logoImage,<br>        embeddedImageStyle: QrEmbeddedImageStyle(<br>          size: Size(60, 60),<br>        ),<br>      );<br><br>      // Generate high-quality PNG<br>      final image = await qrPainter.toImageData(400.0);<br>      final qrBytes = image?.buffer.asUint8List();<br><br>      // Share with native share sheet<br>      await Share.shareXFiles(<br>        [XFile.fromData(<br>          qrBytes!, <br>          name: &#39;my_qr_code.png&#39;, <br>          mimeType: &#39;image/png&#39;<br>        )],<br>        text: description,<br>      );<br><br>      // Clean up<br>      logoImage?.dispose();<br><br>    } catch (e) {<br>      print(&#39;Share failed: $e&#39;);<br>      ScaffoldMessenger.of(this).showSnackBar(<br>        SnackBar(content: Text(&#39;Failed to share QR code&#39;)),<br>      );<br>    }<br>  }<br><br>  Future&lt;ui.Image?&gt; _loadUiImage(String assetPath) async {<br>    try {<br>      final ByteData data = await rootBundle.load(assetPath);<br>      final ui.Codec codec = await ui.instantiateImageCodec(<br>        data.buffer.asUint8List(),<br>        targetWidth: 120,<br>        targetHeight: 120,<br>      );<br>      final ui.FrameInfo frame = await codec.getNextFrame();<br>      return frame.image;<br>    } catch (e) {<br>      print(&#39;Failed to load logo: $e&#39;);<br>      return null;<br>    }<br>  }<br>}</pre><h3>✨ Key Features Explained</h3><h3>1. Custom Styling</h3><pre>eyeStyle: QrEyeStyle(eyeShape: QrEyeShape.square, color: primary)<br>dataModuleStyle: QrDataModuleShape.square</pre><ul><li>Square finder patterns &amp; data modules</li><li>Brand colors throughout</li><li>Consistent professional look</li></ul><pre>embeddedImage: AssetImage(&#39;assets/logo.png&#39;),<br>embeddedImageStyle: QrEmbeddedImageStyle(size: Size.square(60)),</pre><ul><li>Perfectly centered logo</li><li>Automatically error-corrected positioning</li></ul><h3>3. ValueListenableBuilder</h3><pre>ValueListenableBuilder&lt;String&gt;(<br>  valueListenable: qrDataNotifier,<br>  builder: (context, qrData, child) {<br>    return QrImageView(data: qrData...);<br>  },<br>)</pre><ul><li>Reactive updates — QR regenerates instantly</li><li>Performance optimized — only rebuilds QR widget</li></ul><h3>4. Production Sharing</h3><ul><li>Generates 400x400 PNG (perfect for all platforms)</li><li>Native share sheet integration</li><li>Custom filename &amp; MIME type</li><li>Automatic logo disposal (memory safe)</li></ul><h3>🚀 Pro Tips</h3><ol><li>Add to pubspec.yaml assets:</li></ol><pre>flutter:<br>  assets:<br>    - assets/logo.png</pre><ol><li>Error Handling:</li></ol><pre>if (qrData.isEmpty) return; // Before sharing</pre><ol><li>Dynamic Sizing:</li></ol><pre>final size = MediaQuery.of(context).size.width * 0.7;</pre><ol><li>Custom Colors:</li></ol><pre>color: Theme.of(context).primaryColor</pre><h3>📱 Demo Result</h3><p>Your users get:</p><ul><li>✅ Beautiful branded QR codes</li><li>✅ One-tap sharing to WhatsApp/iMessage/etc.</li><li>✅ Perfect logo centering</li><li>✅ Native platform experience</li></ul><p>Copy-paste ready! Perfect for portfolios, business cards, payment apps, or any Flutter project needing QR sharing. 🎉</p><p>Questions? Drop them below! 👇</p><ol><li>Add to pubspec.yaml assets:</li></ol><pre>yaml</pre><pre>Copy code</pre><pre>flutter:<br>  assets:<br>    - assets/logo.png</pre><ol><li>Error Handling:</li></ol><pre>dart</pre><pre>Copy code</pre><pre>if (qrData.isEmpty) return; // Before sharing</pre><ol><li>Dynamic Sizing:</li></ol><pre>dart</pre><pre>Copy code</pre><pre>final size = MediaQuery.of(context).size.width * 0.7;</pre><ol><li>Custom Colors:</li></ol><pre>dart</pre><pre>Copy code</pre><pre>color: Theme.of(context).primaryColor</pre><h3>📱 Demo Result</h3><p>Your users get:</p><ul><li>✅ Beautiful branded QR codes</li><li>✅ One-tap sharing to WhatsApp/iMessage/etc.</li><li>✅ Perfect logo centering</li><li>✅ Native platform experience</li></ul><p>Copy-paste ready! Perfect for portfolios, business cards, payment apps, or any Flutter project needing QR sharing. 🎉</p><p>Questions? Drop them below! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f7197c734c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SIM Change Detector in Android: A Complete Guide]]></title>
            <link>https://medium.com/@tungenwarkartick/sim-change-detector-in-android-a-complete-guide-a258019dbb6e?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a258019dbb6e</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 07:41:42 GMT</pubDate>
            <atom:updated>2026-02-20T07:41:42.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*65OKVQbWiSYuAdtiWtJb2g.jpeg" /></figure><h3>Introduction</h3><p>Have you ever wondered how to detect SIM card changes in an Android app, especially on devices with dual SIM support? Whether you’re building a security app, a banking application, or a subscription-based service, detecting SIM changes is crucial for protecting user accounts and ensuring device integrity.</p><p>In this article, I’ll walk you through building a robust dual SIM change detector in Android that works seamlessly across different Android versions and handles the tricky permission requirements introduced in Android 10+.</p><h3>The Problem</h3><p>Recently, I was working on a Tatasky broadband application where we needed to:</p><ol><li>Detect when a user changes their SIM card</li><li>Support dual SIM devices</li><li>Handle Android’s strict permission policies for device identifiers</li><li>Show an alert when SIM changes are detected</li></ol><p>The challenge? Android has significantly restricted access to device identifiers like SIM serial numbers starting from Android 10 (API 29). A simple call to telephonyManager.getSimSerialNumber() now throws a SecurityException unless your app meets specific privilege requirements.</p><h3>The Journey</h3><h3>Phase 1: Understanding the Restrictions</h3><pre>// This will fail on Android 10+ without proper permissions<br>String simSerial = telephonyManager.getSimSerialNumber();<br>// SecurityException: The user 11959 does not meet the requirements to access device identifiers</pre><p>Android’s privacy changes mean we can’t directly access:</p><ul><li>SIM Serial Number (ICCID)</li><li>IMEI/MEID</li><li>IMSI</li></ul><p>But there’s a solution! We can use the Subscription Manager API which provides subscription-based identifiers that don&#39;t require privileged access.</p><h3>Phase 2: Building the Solution</h3><h4>Step 1: The SimInfo Model Class</h4><pre>public class SimInfo {<br>    private String simSerialNumber;<br>    private String simOperator;<br>    private String simOperatorName;<br>    private String iccId;<br>    private long subscriptionId;<br>    private int simSlotIndex;<br>    private String phoneNumber;<br><br><br>    public int getSimSlotIndex() {<br>        return simSlotIndex;<br>    }<br><br>    public void setSimSlotIndex(int simSlotIndex) {<br>        this.simSlotIndex = simSlotIndex;<br>    }<br><br>    public String getPhoneNumber() {<br>        return phoneNumber;<br>    }<br><br>    public void setPhoneNumber(String phoneNumber) {<br>        this.phoneNumber = phoneNumber;<br>    }<br>    public String getSimSerialNumber() {<br>        return simSerialNumber;<br>    }<br><br>    public void setSimSerialNumber(String simSerialNumber) {<br>        this.simSerialNumber = simSerialNumber;<br>    }<br><br>    public String getSimOperator() {<br>        return simOperator;<br>    }<br><br>    public void setSimOperator(String simOperator) {<br>        this.simOperator = simOperator;<br>    }<br><br>    public String getSimOperatorName() {<br>        return simOperatorName;<br>    }<br><br>    public void setSimOperatorName(String simOperatorName) {<br>        this.simOperatorName = simOperatorName;<br>    }<br><br>    public String getIccId() {<br>        return iccId;<br>    }<br><br>    public void setIccId(String iccId) {<br>        this.iccId = iccId;<br>    }<br><br>    public long getSubscriptionId() {<br>        return subscriptionId;<br>    }<br><br>    public void setSubscriptionId(int subscriptionId) {<br>        this.subscriptionId = subscriptionId;<br>    }<br><br>    public String getSimSubscriberId() {<br>        return simSubscriberId;<br>    }<br><br>    public void setSimSubscriberId(String simSubscriberId) {<br>        this.simSubscriberId = simSubscriberId;<br>    }<br><br>    private String simSubscriberId;<br>}</pre><h4>Step 2: The SimChangeDetector Class</h4><p>Here’s the complete implementation:</p><pre>import android.Manifest;<br>import android.annotation.SuppressLint;<br>import android.content.Context;<br>import android.content.SharedPreferences;<br>import android.os.Build;<br>import android.provider.Settings;<br>import android.telephony.SubscriptionInfo;<br>import android.telephony.SubscriptionManager;<br>import android.telephony.TelephonyManager;<br>import android.util.Log;<br><br>import androidx.annotation.RequiresPermission;<br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>public class SimChangeDetector {<br><br>    private static final String TAG = &quot;SimChangeDetector&quot;;<br>    private static final String PREFS_NAME = &quot;SimSecurityPrefs&quot;;<br>    private static final String KEY_SIM_SERIAL_1 = &quot;sim_serial_number_1&quot;;<br>    private static final String KEY_SIM_SERIAL_2 = &quot;sim_serial_number_2&quot;;<br>    private static final String KEY_SIM_OPERATOR_1 = &quot;sim_operator_1&quot;;<br>    private static final String KEY_SIM_OPERATOR_2 = &quot;sim_operator_2&quot;;<br>    private static final String KEY_SUBSCRIPTION_ID_1 = &quot;subscription_id_1&quot;;<br>    private static final String KEY_SUBSCRIPTION_ID_2 = &quot;subscription_id_2&quot;;<br>    private static final String KEY_SIM_COUNT = &quot;sim_count&quot;;<br><br>    private Context context;<br>    private TelephonyManager telephonyManager;<br>    private SharedPreferences sharedPreferences;<br><br>    public SimChangeDetector(Context context) {<br>        this.context = context;<br>        this.telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);<br>        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);<br>    }<br><br>    // Method to get current SIM information for all SIMs<br>    @SuppressLint(&quot;HardwareIds&quot;)<br>    public List&lt;SimInfo&gt; getCurrentSimInfoList() {<br>        List&lt;SimInfo&gt; simInfoList = new ArrayList&lt;&gt;();<br><br>        try {<br>            String simSerial = null;<br>            try {<br>                simSerial = telephonyManager.getSimSerialNumber();<br>            } catch (SecurityException e) {<br>                // Fall-back to ANDROID_ID if SIM serial is not available<br>                simSerial = Settings.Secure.getString(context.getContentResolver(),<br>                        Settings.Secure.ANDROID_ID);<br>                Log.d(TAG, &quot;Using ANDROID_ID as fallback: &quot; + simSerial);<br>            }<br><br>            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP_MR1) {<br>                SubscriptionManager subscriptionManager = (SubscriptionManager)<br>                        context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);<br><br>                List&lt;SubscriptionInfo&gt; subscriptionInfoList =<br>                        subscriptionManager.getActiveSubscriptionInfoList();<br><br>                if (subscriptionInfoList != null &amp;&amp; !subscriptionInfoList.isEmpty()) {<br>                    int simCount = subscriptionInfoList.size();<br>                    Log.d(TAG, &quot;Number of SIMs detected: &quot; + simCount);<br><br>                    for (int i = 0; i &lt; subscriptionInfoList.size(); i++) {<br>                        SubscriptionInfo info = subscriptionInfoList.get(i);<br>                        SimInfo simInfo = new SimInfo();<br><br>                        // Set SIM slot number (0 = SIM 1, 1 = SIM 2)<br>                        simInfo.setSimSlotIndex(info.getSimSlotIndex());<br><br>                        // Get ICC ID (requires READ_PHONE_STATE permission)<br>                        try {<br>                            simInfo.setIccId(info.getIccId());<br>                        } catch (SecurityException e) {<br>                            Log.w(TAG, &quot;Cannot get ICC ID for SIM &quot; + (i + 1));<br>                            simInfo.setIccId(null);<br>                        }<br><br>                        // Get subscription ID (unique per SIM)<br>                        simInfo.setSubscriptionId(info.getSubscriptionId());<br><br>                        // Get SIM serial number<br>                        // For dual SIM, we use subscription ID as identifier<br>                        simInfo.setSimSerialNumber(String.valueOf(info.getSubscriptionId()));<br><br>                        // Get SIM operator<br>                        simInfo.setSimOperator(info.getMcc() + &quot;&quot; + info.getMnc());<br>                        simInfo.setSimOperatorName((String) info.getCarrierName());<br><br>                        // Get phone number if available<br>                        simInfo.setPhoneNumber(info.getNumber());<br><br>                        simInfoList.add(simInfo);<br><br>                        Log.d(TAG, &quot;SIM &quot; + (i + 1) + &quot; - Slot: &quot; + info.getSimSlotIndex() +<br>                                &quot;, SubID: &quot; + info.getSubscriptionId() +<br>                                &quot;, Operator: &quot; + simInfo.getSimOperator() +<br>                                &quot;, Carrier: &quot; + simInfo.getSimOperatorName());<br>                    }<br>                } else {<br>                    Log.d(TAG, &quot;No active SIMs found&quot;);<br>                }<br>            }<br>        } catch (SecurityException e) {<br>            Log.e(TAG, &quot;SecurityException: &quot; + e.getMessage());<br>        }<br><br>        return simInfoList;<br>    }<br><br>    // Get single SIM info (backward compatibility)<br>    public SimInfo getCurrentSimInfo() {<br>        List&lt;SimInfo&gt; simList = getCurrentSimInfoList();<br>        if (simList != null &amp;&amp; !simList.isEmpty()) {<br>            return simList.get(0); // Return first SIM<br>        }<br>        return null;<br>    }<br><br>    // Save current SIM information for all SIMs<br>    public void saveCurrentSimInfo() {<br>        List&lt;SimInfo&gt; simInfoList = getCurrentSimInfoList();<br><br>        if (simInfoList == null || simInfoList.isEmpty()) {<br>            Log.w(TAG, &quot;No SIM info to save&quot;);<br>            return;<br>        }<br><br>        SharedPreferences.Editor editor = sharedPreferences.edit();<br><br>        // Save number of SIMs<br>        editor.putInt(KEY_SIM_COUNT, simInfoList.size());<br><br>        // Save each SIM&#39;s information<br>        for (int i = 0; i &lt; simInfoList.size(); i++) {<br>            SimInfo simInfo = simInfoList.get(i);<br>            String suffix = (i == 0) ? &quot;1&quot; : &quot;2&quot;; // SIM 1 or SIM 2<br><br>            if (simInfo.getSimSerialNumber() != null) {<br>                editor.putString(KEY_SIM_SERIAL_1 + suffix.replace(&quot;1&quot;, &quot;&quot;),<br>                        simInfo.getSimSerialNumber());<br>            }<br>            if (simInfo.getSimOperator() != null) {<br>                editor.putString(KEY_SIM_OPERATOR_1 + suffix.replace(&quot;1&quot;, &quot;&quot;),<br>                        simInfo.getSimOperator());<br>            }<br>            editor.putLong(KEY_SUBSCRIPTION_ID_1 + suffix.replace(&quot;1&quot;, &quot;&quot;),<br>                    simInfo.getSubscriptionId());<br>        }<br><br>        editor.apply();<br>        Log.d(TAG, &quot;SIM information saved for &quot; + simInfoList.size() + &quot; SIM(s)&quot;);<br>    }<br><br>    // Check if any SIM has changed (dual SIM compatible)<br>    public boolean hasSimChanged() {<br>        List&lt;SimInfo&gt; currentSimList = getCurrentSimInfoList();<br><br>        if (currentSimList == null || currentSimList.isEmpty()) {<br>            Log.e(TAG, &quot;Could not get current SIM info&quot;);<br>            return false;<br>        }<br><br>        int savedSimCount = sharedPreferences.getInt(KEY_SIM_COUNT, 0);<br><br>        // Check if number of SIMs changed<br>        if (savedSimCount != currentSimList.size()) {<br>            Log.d(TAG, &quot;SIM count changed: saved=&quot; + savedSimCount +<br>                    &quot;, current=&quot; + currentSimList.size());<br>            return true;<br>        }<br><br>        // Compare each SIM<br>        for (int i = 0; i &lt; currentSimList.size(); i++) {<br>            SimInfo currentSim = currentSimList.get(i);<br>            String suffix = (i == 0) ? &quot;1&quot; : &quot;2&quot;;<br><br>            long savedSubscriptionId = sharedPreferences.getLong(<br>                    KEY_SUBSCRIPTION_ID_1 + suffix.replace(&quot;1&quot;, &quot;&quot;), -1);<br>            String savedOperator = sharedPreferences.getString(<br>                    KEY_SIM_OPERATOR_1 + suffix.replace(&quot;1&quot;, &quot;&quot;), null);<br><br>            // If first time, no previous data<br>            if (savedSubscriptionId == -1 &amp;&amp; savedOperator == null) {<br>                Log.d(TAG, &quot;No previous SIM information found for SIM &quot; + (i + 1));<br>                return false;<br>            }<br><br>            // Compare subscription ID<br>            if (savedSubscriptionId != -1 &amp;&amp;<br>                    savedSubscriptionId != currentSim.getSubscriptionId()) {<br>                Log.d(TAG, &quot;SIM changed in slot &quot; + (i + 1) +<br>                        &quot;: SubID mismatch - saved: &quot; + savedSubscriptionId +<br>                        &quot;, current: &quot; + currentSim.getSubscriptionId());<br>                return true;<br>            }<br><br>            // Compare operator<br>            if (savedOperator != null &amp;&amp; currentSim.getSimOperator() != null) {<br>                if (!savedOperator.equals(currentSim.getSimOperator())) {<br>                    Log.d(TAG, &quot;SIM changed in slot &quot; + (i + 1) +<br>                            &quot;: Operator mismatch&quot;);<br>                    return true;<br>                }<br>            }<br>        }<br><br>        Log.d(TAG, &quot;No SIM changes detected&quot;);<br>        return false;<br>    }<br><br>    // Check if a specific SIM slot has changed<br>    public boolean hasSimChanged(int slotIndex) {<br>        List&lt;SimInfo&gt; currentSimList = getCurrentSimInfoList();<br><br>        if (currentSimList == null || currentSimList.isEmpty()) {<br>            return false;<br>        }<br><br>        // Find SIM in the requested slot<br>        SimInfo targetSim = null;<br>        for (SimInfo sim : currentSimList) {<br>            if (sim.getSimSlotIndex() == slotIndex) {<br>                targetSim = sim;<br>                break;<br>            }<br>        }<br><br>        if (targetSim == null) {<br>            // SIM removed from slot<br>            Log.d(TAG, &quot;SIM removed from slot &quot; + slotIndex);<br>            return true;<br>        }<br><br>        String suffix = (slotIndex == 0) ? &quot;1&quot; : &quot;2&quot;;<br>        long savedSubscriptionId = sharedPreferences.getLong(<br>                KEY_SUBSCRIPTION_ID_1 + suffix.replace(&quot;1&quot;, &quot;&quot;), -1);<br><br>        if (savedSubscriptionId == -1) {<br>            return false; // First time<br>        }<br><br>        return savedSubscriptionId != targetSim.getSubscriptionId();<br>    }<br><br>    // Get the number of active SIMs<br>    @RequiresPermission(Manifest.permission.READ_PHONE_STATE)<br>    public int getActiveSimCount() {<br>        SubscriptionManager subscriptionManager = (SubscriptionManager)<br>                context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);<br>        List&lt;SubscriptionInfo&gt; list = subscriptionManager.getActiveSubscriptionInfoList();<br>        return (list != null) ? list.size() : 0;<br>    }<br><br>    // Clear saved SIM information<br>    public void clearSavedSimInfo() {<br>        sharedPreferences.edit().clear().apply();<br>        Log.d(TAG, &quot;Saved SIM information cleared&quot;);<br>    }<br><br>    // Check if this is first time SIM detection<br>    public boolean isFirstTime() {<br>        return sharedPreferences.getInt(KEY_SIM_COUNT, 0) == 0;<br>    }<br>}</pre><h4>Step 3: The SimChangeReceiver (BroadcastReceiver)</h4><p>This receiver listens for SIM state changes and triggers the detection logic:</p><pre>import android.content.BroadcastReceiver;<br>import android.content.Context;<br>import android.content.Intent;<br><br>import android.util.Log;<br><br>public class SimChangeReceiver extends BroadcastReceiver {<br><br>    private static final String TAG = &quot;SimChangeReceiver&quot;;<br>    private static final String ACTION_SIM_STATE_CHANGED = &quot;android.intent.action.SIM_STATE_CHANGED&quot;;<br>    private static final String ACTION_PHONE_STATE = &quot;android.intent.action.PHONE_STATE&quot;;<br><br>    private OnSimChangeListener listener;<br><br>    public interface OnSimChangeListener {<br>        void onSimChanged(String message);<br>        void onSimNotChanged();<br>    }<br><br>    public void setOnSimChangeListener(OnSimChangeListener listener) {<br>        this.listener = listener;<br>    }<br><br>    @Override<br>    public void onReceive(Context context, Intent intent) {<br>        if (intent == null) return;<br><br>        String action = intent.getAction();<br><br>        if (ACTION_SIM_STATE_CHANGED.equals(action)) {<br>            handleSimStateChanged(context, intent);<br>        }<br>    }<br><br>    private void handleSimStateChanged(Context context, Intent intent) {<br>        String state = intent.getStringExtra(&quot;ss&quot;);<br><br>        Log.d(TAG, &quot;SIM State: &quot; + state);<br><br>        // Check if SIM is ready (loaded)<br>        if (&quot;LOADED&quot;.equals(state) || &quot;READY&quot;.equals(state)) {<br>            // Give some time for SIM to be fully initialized<br>            new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -&gt; {<br>                checkSimChange(context);<br>            }, 2000);<br>        }<br><br>        if(&quot;android.intent.action.SIM_STATE_CHANGED&quot;.equals(intent.getAction())){<br>            new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -&gt; {<br>                checkSimChange(context);<br>            }, 2000);<br>        }<br>    }<br><br><br>    private void checkSimChange(Context context) {<br>        SimChangeDetector detector = new SimChangeDetector(context);<br><br>        if (detector.hasSimChanged()) {<br>            Log.d(TAG, &quot;SIM has been changed!&quot;);<br>            if (listener != null) {<br>                listener.onSimChanged(&quot;SIM card has been changed!&quot;);<br>            }<br><br>            // Update saved SIM info to new one<br>            detector.saveCurrentSimInfo();<br>        } else {<br>            Log.d(TAG, &quot;SIM has not changed&quot;);<br>            if (listener != null) {<br>                listener.onSimNotChanged();<br>            }<br>        }<br>    }<br>}</pre><h3>Phase 3: Registering the BroadcastReceiver</h3><h4>AndroidManifest.xml Configuration</h4><pre>&lt;receiver <br>    android:name=&quot;.application.SimChangeReceiver&quot; <br>    android:exported=&quot;false&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.SIM_STATE_CHANGED&quot; /&gt;<br>        &lt;action android:name=&quot;android.intent.action.PHONE_STATE&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/receiver&gt;</pre><h4>Or Register Dynamically in Activity/Application</h4><pre>public class MainActivity extends AppCompatActivity {<br><br>    private SimChangeReceiver simChangeReceiver;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.activity_main);<br><br>        // Initialize detector<br>        SimChangeDetector detector = new SimChangeDetector(this);<br><br>        // Save initial SIM info (first time setup)<br>        if (detector.isFirstTime()) {<br>            detector.saveCurrentSimInfo();<br>        }<br><br>        // Register receiver<br>        registerSimChangeReceiver();<br>    }<br><br>    private void registerSimChangeReceiver() {<br>        simChangeReceiver = new SimChangeReceiver();<br>        <br>        // Set listener for callback<br>        simChangeReceiver.setOnSimChangeListener(new SimChangeReceiver.OnSimChangeListener() {<br>            @Override<br>            public void onSimChanged(String message) {<br>                Log.d(&quot;MainActivity&quot;, &quot;SIM Changed: &quot; + message);<br>                showSimChangedDialog(message);<br>            }<br><br>            @Override<br>            public void onSimNotChanged() {<br>                Log.d(&quot;MainActivity&quot;, &quot;SIM not changed&quot;);<br>            }<br>        });<br><br>        // Register the receiver<br>        IntentFilter filter = new IntentFilter();<br>        filter.addAction(&quot;android.intent.action.SIM_STATE_CHANGED&quot;);<br>        filter.addAction(&quot;android.intent.action.PHONE_STATE&quot;);<br>        <br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>            registerReceiver(simChangeReceiver, filter, Context.RECEIVER_NOT_EXPORTED);<br>        } else {<br>            registerReceiver(simChangeReceiver, filter);<br>        }<br>    }<br><br>    @Override<br>    protected void onDestroy() {<br>        super.onDestroy();<br>        // Unregister receiver<br>        if (simChangeReceiver != null) {<br>            try {<br>                unregisterReceiver(simChangeReceiver);<br>            } catch (Exception e) {<br>                Log.e(&quot;MainActivity&quot;, &quot;Error unregistering receiver: &quot; + e.getMessage());<br>            }<br>        }<br>    }<br><br>    private void showSimChangedDialog(String message) {<br>        new</pre><h3>Conclusion</h3><p>Building a dual SIM change detector doesn’t have to be complicated. By leveraging the Subscription Manager API and understanding Android&#39;s privacy changes, we can create a robust solution that:</p><p>✅ Works on dual SIM devices<br>✅ Handles Android 10+ restrictions<br>✅ Provides alerts on UI thread<br>✅ Uses unique subscription identifiers<br>✅ Persists SIM information across app restarts</p><p>The complete code is now ready for you to integrate into your Android application. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a258019dbb6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Firebase Analytics to a Flutter App for Android and iOS]]></title>
            <link>https://medium.com/@tungenwarkartick/adding-firebase-analytics-to-a-flutter-app-for-android-and-ios-aa3382637a10?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa3382637a10</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 17:30:38 GMT</pubDate>
            <atom:updated>2026-02-08T17:30:38.035Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide walks you through integrating Firebase Analytics into a Flutter app to track user interactions, events, and app performance. Firebase Analytics provides insights into user behavior, helping you optimize your app. We’ll cover setup for both Android and iOS platforms. This assumes you have a basic Flutter app and are familiar with Dart. If you haven’t set up Firebase yet, follow the initial steps from the Google Sign-In guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coDWXsxstVEJAAR2ETyUdA.png" /></figure><h3>Prerequisites</h3><ul><li>Flutter SDK installed (version 3.0 or later recommended).</li><li>FlutterFire CLI installed: Run dart pub global activate flutterfire_cli.</li><li>A Google account for Firebase Console.</li><li>Android Studio for Android setup.</li><li>Xcode for iOS setup (macOS required).</li><li>A Firebase project: Create or use an existing one at Firebase Console.</li></ul><h3>Step 1: Set Up Firebase Project</h3><ol><li>In Firebase Console, create a new project or select an existing one.</li><li>Enable Analytics:</li></ol><ul><li>Go to Analytics &gt; Dashboard (it may auto-enable if you add an app).</li></ul><ol><li>Add your app to Firebase:</li></ol><ul><li>For Android: Click Add app &gt; Android, enter your package name (e.g., com.example.myapp), download google-services.json, and place it in android/app/.</li><li>For iOS: Click Add app &gt; iOS, enter your bundle ID (e.g., com.example.myapp), download GoogleService-Info.plist, and place it in ios/Runner/.</li></ul><ol><li>Generate firebase_options.dart:</li></ol><ul><li>Run flutterfire configure in your project root. This will create/update lib/firebase_options.dart with the provided options.</li></ul><h3>Step 2: Configure Android</h3><ol><li>In android/app/build.gradle, add the Google Services plugin (if not already added):</li></ol><pre>dependencies {<br>    // ... other dependencies<br>    classpath &#39;com.google.gms:google-services:4.3.15&#39;<br>}</pre><p>At the bottom of the file:</p><pre>apply plugin: &#39;com.google.gms.google-services&#39;</pre><p>2. In android/app/src/main/AndroidManifest.xml, ensure internet permission is present:</p><p>In android/app/src/main/AndroidManifest.xml, ensure internet permission is present:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><p>3. For SHA-1 fingerprint (if not done for Sign-In):</p><ul><li>Run in terminal: keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android.</li><li>Add the SHA-1 to Firebase under Project settings &gt; General &gt; Your apps &gt; Android app.</li></ul><h3>Step 3: Configure iOS</h3><ol><li>In Xcode, open your Flutter iOS project (ios/Runner.xcworkspace).</li><li>Ensure GoogleService-Info.plist is added to the project (drag it into Xcode if needed).</li><li>No additional URL schemes are needed for Analytics, but if you’re also using Sign-In, refer to the previous guide.</li><li>Enable Keychain Sharing if desired for data persistence (optional).</li></ol><h3>Step 4: Add Dependencies to Flutter Project</h3><p>In pubspec.yaml, add:</p><pre>dependencies:<br>  firebase_core: ^2.15.0<br>  firebase_analytics: ^10.4.5</pre><p>Run flutter pub get.</p><h3>Step 5: Implement Firebase Analytics in Flutter Code</h3><p>Create or update lib/firebase_options.dart with the provided content (ensure it&#39;s in your project). Then, initialize Firebase in main.dart using the options and set up analytics tracking:</p><pre>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:firebase_analytics/firebase_analytics.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;firebase_options.dart&#39;; // Import the generated options file<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp(<br>    options: DefaultFirebaseOptions.currentPlatform, // Use platform-specific options<br>  );<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  final FirebaseAnalytics analytics = FirebaseAnalytics.instance;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      navigatorObservers: [<br>        FirebaseAnalyticsObserver(analytics: analytics), // Tracks screen views<br>      ],<br>      home: HomePage(analytics: analytics),<br>    );<br>  }<br>}<br><br>class HomePage extends StatelessWidget {<br>  final FirebaseAnalytics analytics;<br><br>  HomePage({required this.analytics});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;Firebase Analytics Demo&#39;)),<br>      body: Center(<br>        child: ElevatedButton(<br>          onPressed: () async {<br>            // Log a custom event<br>            await analytics.logEvent(<br>              name: &#39;button_click&#39;,<br>              parameters: {&#39;button_name&#39;: &#39;demo_button&#39;},<br>            );<br>            print(&#39;Event logged&#39;);<br>          },<br>          child: Text(&#39;Log Event&#39;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><ul><li>Key Features:</li><li>Automatic tracking: Screen views are tracked via FirebaseAnalyticsObserver.</li><li>Custom events: Use analytics.logEvent() to track user actions (e.g., button clicks, purchases).</li><li>User properties: Set properties like await analytics.setUserProperty(name: &#39;user_type&#39;, value: &#39;premium&#39;);.</li><li>Consent: For GDPR compliance, use await analytics.setAnalyticsCollectionEnabled(true); (default is enabled).</li><li>Platform-specific options: The firebase_options.dart file ensures the correct API keys and IDs are used for Android and iOS (e.g., projectId: &#39;neeti-1cd8f&#39;, iosBundleId: &#39;com.mobicule.neeti&#39;).</li></ul><h3>Step 6: Testing</h3><ul><li>Android: Run flutter run on an emulator or device. Check Firebase Console &gt; Analytics &gt; Dashboard for real-time events after interactions.</li><li>iOS: Run on a simulator or device. Events should appear in Firebase Console within minutes.</li><li>Use Debug Mode for testing:</li><li>Android: Run adb shell setprop debug.firebase.analytics.app com.example.myapp (replace with your package name).</li><li>iOS: Add -FIRAnalyticsDebugEnabled to your scheme&#39;s arguments in Xcode.</li><li>View logs in Android Studio Logcat or Xcode Console for confirmation.</li></ul><h3>Troubleshooting Tips</h3><ul><li>Events Not Appearing: Wait up to 24 hours for data to process. Ensure internet connection and correct Firebase project. Verify firebase_options.dart matches your Firebase Console settings.</li><li>Initialization Errors: Double-check google-services.json and GoogleService-Info.plist are in place. If SHA-1 is missing, add it as per Step 2.</li><li>Platform Differences: Android requires Google Play Services; iOS works natively. The options file handles differences automatically.</li><li>Common Issues: Outdated dependencies — update to latest. For privacy, disable analytics in dev builds: await analytics.setAnalyticsCollectionEnabled(false);.</li><li>Debugging: Add print statements or use Firebase&#39;s debug mode. If flutterfire configure fails, ensure your Firebase project is linked correctly.</li></ul><p>This setup enables basic analytics tracking with secure, platform-specific configuration. For advanced features like A/B testing or custom audiences, explore Firebase Console. Refer to the Firebase Analytics Flutter docs for more. If you encounter issues, share error logs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa3382637a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Google Sign-In to a Flutter App for Android and IOS]]></title>
            <link>https://medium.com/@tungenwarkartick/adding-google-sign-in-to-a-flutter-app-for-android-and-ios-ec37e9aeec7a?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec37e9aeec7a</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 16:08:05 GMT</pubDate>
            <atom:updated>2026-02-08T16:11:04.658Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide walks you through integrating Google Sign-In into a Flutter app, enabling users to authenticate via their Google accounts. We’ll cover setup for both Android and iOS platforms, using Firebase Authentication for backend support. This process assumes you have a basic Flutter app set up and are familiar with Dart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*MqbTsRFU7uwx-vn1PvAHqA.jpeg" /></figure><h3>Prerequisites</h3><ul><li>Flutter SDK installed (version 3.0 or later recommended).</li><li>A Google account for Firebase and Google Cloud Console.</li><li>Android Studio for Android setup.</li><li>Xcode for iOS setup (macOS required).</li><li>A Firebase project: Create one at Firebase Console.</li></ul><h3>Step 1: Set Up Firebase Project</h3><ol><li>In Firebase Console, create a new project or select an existing one.</li><li>Enable Google Sign-In:</li></ol><ul><li>Go to Authentication &gt; Sign-in method &gt; Enable Google.</li></ul><p>3. Add your app to Firebase:</p><ul><li>For Android: Click Add app &gt; Android, enter your package name (e.g., com.example.myapp), download google-services.json, and place it in android/app/.</li><li>For iOS: Click Add app &gt; iOS, enter your bundle ID (e.g., com.example.myapp), download GoogleService-Info.plist, and place it in ios/Runner/.</li></ul><h3>Step 2: Configure Android</h3><ol><li>In android/app/build.gradle, add the Google Services plugin:</li></ol><pre>dependencies {<br>    // ... other dependencies<br>    classpath &#39;com.google.gms:google-services:4.3.15&#39;<br>}</pre><p>At the bottom of the file:</p><pre>apply plugin: &#39;com.google.gms.google-services&#39;</pre><p>2. In android/app/src/main/AndroidManifest.xml, add internet permission if not present:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><p>3. For SHA-1 fingerprint (needed for Google Sign-In):</p><ul><li>Open your terminal and run the following command to get the SHA1 for the debug keystore:</li></ul><pre>keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android</pre><ul><li>This will output the SHA1 fingerprint (among other details). Copy the SHA1 value (e.g., AA:BB:CC:...).</li><li>If you’re using a release keystore, replace ~/.android/debug.keystore with your release keystore path and provide the correct alias, storepass, and keypass.</li><li>Add this SHA-1 to your Firebase project under Project settings &gt; General &gt; Your apps &gt; Android app.</li></ul><h3>Step 3: Configure iOS</h3><ol><li>In Xcode, open your Flutter iOS project (ios/Runner.xcworkspace).</li><li>Add custom URL schemes:</li></ol><ul><li>In Info.plist, add:</li></ul><pre>&lt;key&gt;CFBundleURLTypes&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;dict&gt;<br>        &lt;key&gt;CFBundleTypeRole&lt;/key&gt;<br>        &lt;string&gt;Editor&lt;/string&gt;<br>        &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;<br>        &lt;array&gt;<br>            &lt;string&gt;com.googleusercontent.apps.YOUR_CLIENT_ID&lt;/string&gt;<br>        &lt;/array&gt;<br>    &lt;/dict&gt;<br>&lt;/array&gt;</pre><ul><li>Replace YOUR_CLIENT_ID with the iOS client ID from Firebase Console (Project settings &gt; General &gt; Your apps &gt; iOS app).</li><li>Enable Keychain Sharing (optional but recommended for persistence):</li><li>In Xcode, go to Runner &gt; Capabilities &gt; Enable Keychain Sharing.</li><li>Note on SHA1 for iOS: Unlike Android, iOS does not require a SHA1 fingerprint for Firebase setup. The authentication is handled via the bundle ID and the GoogleService-Info.plist file. However, if you need to generate a certificate fingerprint for other purposes (e.g., advanced Firebase features), you can use the following terminal command to get the SHA1 of your iOS certificate:</li><li>First, export your certificate from Keychain Access (macOS) as a .p12 file.</li><li>Then, in terminal, run:</li></ul><pre>openssl pkcs12 -in your_certificate.p12 -out certificate.pem -nodes<br>openssl x509 -in certificate.pem -fingerprint -sha1 -noout</pre><ul><li>This will output the SHA1 fingerprint. Note: This is rarely needed for standard Google Sign-In in Flutter/iOS; Firebase handles it automatically.</li></ul><h3>Step 4: Add Dependencies to Flutter Project</h3><p>In pubspec.yaml, add:</p><pre>dependencies:<br>  firebase_core: ^2.15.0<br>  firebase_auth: ^4.7.2<br>  google_sign_in: ^6.1.4</pre><p>Run flutter pub get.</p><h3>Step 5: Implement Google Sign-In in Flutter Code</h3><p>Create a new Dart file (e.g., auth_service.dart) for authentication logic:</p><pre>import &#39;package:firebase_auth/firebase_auth.dart&#39;;<br>import &#39;package:google_sign_in/google_sign_in.dart&#39;;<br><br>class AuthService {<br>  final FirebaseAuth _auth = FirebaseAuth.instance;<br>  final GoogleSignIn _googleSignIn = GoogleSignIn();<br><br>  Future&lt;User?&gt; signInWithGoogle() async {<br>    try {<br>      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();<br>      if (googleUser == null) return null;<br><br>      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;<br>      final AuthCredential credential = GoogleAuthProvider.credential(<br>        accessToken: googleAuth.accessToken,<br>        idToken: googleAuth.idToken,<br>      );<br><br>      final UserCredential userCredential = await _auth.signInWithCredential(credential);<br>      return userCredential.user;<br>    } catch (e) {<br>      print(&#39;Error signing in with Google: $e&#39;);<br>      return null;<br>    }<br>  }<br><br>  Future&lt;void&gt; signOut() async {<br>    await _googleSignIn.signOut();<br>    await _auth.signOut();<br>  }<br>}</pre><p>In your main app (e.g., main.dart), initialize Firebase and use the service:</p><pre>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;auth_service.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp();<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  final AuthService _auth = AuthService();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Scaffold(<br>        appBar: AppBar(title: Text(&#39;Google Sign-In&#39;)),<br>        body: Center(<br>          child: ElevatedButton(<br>            onPressed: () async {<br>              User? user = await _auth.signInWithGoogle();<br>              if (user != null) {<br>                print(&#39;Signed in: ${user.displayName}&#39;);<br>              }<br>            },<br>            child: Text(&#39;Sign in with Google&#39;),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Step 6: Testing</h3><ul><li>Android: Run flutter run on an emulator or device. Ensure the SHA-1 is correct to avoid authentication errors.</li><li>iOS: Run on a simulator or device. If issues arise, check console logs for errors like invalid client ID.</li><li>Test sign-out by calling _auth.signOut().</li></ul><h3>Troubleshooting Tips</h3><ul><li>Common errors: Mismatched package/bundle IDs, missing SHA-1, or outdated dependencies. Check Firebase docs for updates.</li><li>Platform differences: Android uses google-services.json, iOS uses GoogleService-Info.plist. Ensure both are correctly placed.</li><li>Security: Never hardcode client IDs; use Firebase’s generated ones.</li></ul><p>This setup provides a secure, cross-platform Google Sign-In. For more details, refer to the Firebase Flutter docs and Google Sign-In package. If you encounter issues, share error logs for further help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec37e9aeec7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Background Location Tracking in Flutter: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@tungenwarkartick/implementing-background-location-tracking-in-flutter-a-step-by-step-guide-4ac3d6f5fb92?source=rss-9b1784f15bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ac3d6f5fb92</guid>
            <dc:creator><![CDATA[Kartik Tungenwar]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 14:57:17 GMT</pubDate>
            <atom:updated>2026-01-15T15:28:42.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGEKvKXl3JStP0fA4arvrw.png" /></figure><h3>Introduction</h3><p>In today’s mobile app landscape, background location tracking is a crucial feature for apps like ride-sharing, fitness trackers, or delivery services. Flutter, with its cross-platform capabilities, makes it easier to implement this on both Android and iOS. However, handling background tasks, permissions, and platform-specific configurations can be tricky.</p><p>In this tutorial, we’ll build a simple Flutter app that tracks the user’s location in the background using the flutter_foreground_task and geolocator packages. The app will display location updates in a persistent notification and log them to the console. We&#39;ll cover everything from setup to deployment, including common pitfalls and fixes.</p><p>By the end, you’ll have a working app that runs location tracking even when the app is minimized or the screen is off. Let’s dive in!</p><h3>Prerequisites</h3><ul><li>Flutter SDK (version 3.0 or higher recommended).</li><li>Android Studio or VS Code with Flutter extensions.</li><li>A physical Android device for testing (emulators may not handle background services well).</li><li>Basic knowledge of Dart and Flutter widgets.</li></ul><h3>Step 1: Setting Up Dependencies</h3><p>First, create a new Flutter project:</p><pre>flutter create background_location_app<br>cd background_location_app</pre><p>Open pubspec.yaml and add the following dependencies:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  geolocator: ^11.0.0<br>  flutter_foreground_task: ^6.1.1<br>  permission_handler: ^12.0.1</pre><p>Run flutter pub get to install them. These packages handle location services, foreground tasks, and permissions respectively.</p><p>Note: If you encounter build errors (like the ones in the initial query), try flutter clean and flutter pub get again. Issues with Kotlin caches are common—clear android/.gradle and rebuild if needed.</p><h3>Step 2: Configuring Android Permissions and Services</h3><p>For Android, we need to declare permissions and a foreground service in android/app/src/main/AndroidManifest.xml. Add these inside the &lt;manifest&gt; tag:</p><pre>&lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_BACKGROUND_LOCATION&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.WAKE_LOCK&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE_LOCATION&quot;/&gt;</pre><p>Then, inside the &lt;application&gt; tag, add the service:</p><pre>&lt;service android:name=&quot;com.pravera.flutter_foreground_task.service.ForegroundService&quot; android:foregroundServiceType=&quot;location&quot;/&gt;</pre><p>Why these permissions?</p><ul><li>ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION: For basic location access.</li><li>ACCESS_BACKGROUND_LOCATION: Allows location tracking when the app is in the background (required for Android 10+).</li><li>FOREGROUND_SERVICE and related: Enables the app to run a foreground service for persistent notifications.</li><li>WAKE_LOCK: Keeps the device awake during tracking.</li></ul><p>iOS Note: For iOS, add location permissions in ios/Runner/Info.plist (e.g., NSLocationWhenInUseUsageDescription). Background modes need to be enabled in Xcode.</p><h3>Step 3: Implementing the Background Task Handler</h3><p>Now, let’s code the core logic. Replace the contents of lib/main.dart with the following:</p><pre>import &#39;dart:isolate&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_foreground_task/flutter_foreground_task.dart&#39;;<br>import &#39;package:geolocator/geolocator.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>/// Background task handler for location updates<br>@pragma(&#39;vm:entry-point&#39;)<br>class LocationTaskHandler extends TaskHandler {<br>  @override<br>  void onNotificationPressed() {}<br><br>  @override<br>  void onNotificationButtonPressed(String id) {}<br><br>  @override<br>  void onRepeatEvent(DateTime timestamp, SendPort? sendPort) async {<br>    try {<br>      final position = await Geolocator.getCurrentPosition(<br>        desiredAccuracy: LocationAccuracy.high,<br>      );<br>      final lat = position.latitude.toStringAsFixed(5);<br>      final lon = position.longitude.toStringAsFixed(5);<br><br>      // Format the timestamp to a readable time string (HH:MM:SS)<br>      final time = &quot;${timestamp.hour.toString().padLeft(2, &#39;0&#39;)}:${timestamp.minute.toString().padLeft(2, &#39;0&#39;)}:${timestamp.second.toString().padLeft(2, &#39;0&#39;)}&quot;;<br><br>      // Update notification with current location and time<br>      await FlutterForegroundTask.updateService(<br>        notificationText: &#39;Lat: $lat, Lon: $lon at $time&#39;,<br>      );<br><br>      print(&quot;📍 Location: $lat, $lon at $time&quot;);<br>    } catch (e) {<br>      print(&quot;❌ Error getting location: $e&quot;);<br>    }<br>  }<br><br>  @override<br>  void onDestroy(DateTime timestamp, SendPort? sendPort) {}<br><br>  @override<br>  void onStart(DateTime timestamp, SendPort? sendPort) {}<br>}<br><br>@pragma(&#39;vm:entry-point&#39;)<br>void startCallback() {<br>  FlutterForegroundTask.setTaskHandler(LocationTaskHandler());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Background Location&#39;,<br>      debugShowCheckedModeBanner: false,<br>      home: const HomePage(),<br>    );<br>  }<br>}<br><br>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  @override<br>  void initState() {<br>    super.initState();<br>    _initForegroundTask();<br>    _requestPermissions();<br>  }<br><br>  void _initForegroundTask() {<br>    FlutterForegroundTask.init(<br>      androidNotificationOptions: AndroidNotificationOptions(<br>        channelId: &#39;location_channel&#39;,<br>        channelName: &#39;Location Tracking&#39;,<br>        channelDescription: &#39;Getting location updates in background&#39;,<br>        channelImportance: NotificationChannelImportance.LOW,<br>        priority: NotificationPriority.LOW,<br>        enableVibration: false,<br>        playSound: false,<br>        showWhen: true,<br>      ),<br>      iosNotificationOptions: const IOSNotificationOptions(),<br>      foregroundTaskOptions: ForegroundTaskOptions(<br>        interval: 20000,  // Update every 20 seconds<br>        autoRunOnBoot: false,<br>        allowWakeLock: true,<br>      ),<br>    );<br>  }<br><br>  Future&lt;void&gt; _requestPermissions() async {<br>    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();<br>    if (!serviceEnabled) {<br>      await Geolocator.openLocationSettings();<br>    }<br><br>    LocationPermission permission = await Geolocator.checkPermission();<br>    if (permission == LocationPermission.denied ||<br>        permission == LocationPermission.deniedForever) {<br>      await Geolocator.requestPermission();<br>    }<br><br>    final isIgnoring =<br>        await FlutterForegroundTask.isIgnoringBatteryOptimizations;<br>    if (!isIgnoring) {<br>      await FlutterForegroundTask.requestIgnoreBatteryOptimization();<br>    }<br>  }<br><br>  Future&lt;void&gt; _startService() async {<br>    await FlutterForegroundTask.startService(<br>      notificationTitle: &#39;Tracking Location&#39;,<br>      notificationText: &#39;Waiting for location...&#39;,<br>      callback: startCallback,<br>    );<br>  }<br><br>  Future&lt;void&gt; _stopService() async {<br>    await FlutterForegroundTask.stopService();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&quot;Background Location&quot;)),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            ElevatedButton(<br>              onPressed: _startService,<br>              child: const Text(&#39;Start Background Location&#39;),<br>            ),<br>            const SizedBox(height: 20),<br>            ElevatedButton(<br>              onPressed: _stopService,<br>              child: const Text(&#39;Stop&#39;),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Key Breakdown:</h3><ul><li>LocationTaskHandler: Extends TaskHandler and overrides onRepeatEvent to fetch location every 20 seconds, update the notification, and print to console.</li><li>startCallback: Registers the handler when the service starts.</li><li>_initForegroundTask: Configures the foreground service with low-priority notifications to avoid disturbing the user.</li><li>_requestPermissions: Checks and requests location permissions, and asks to ignore battery optimizations for reliable background tracking.</li><li>UI: Simple buttons to start/stop the service.</li></ul><p>Pro Tip: The @pragma(&#39;vm:entry-point&#39;) ensures the code runs in a separate isolate, preventing UI blocking.</p><h3>Step 4: Testing and Troubleshooting</h3><ol><li>Run the App: Use flutter run on a physical device. Grant permissions when prompted.</li><li>Start Tracking: Tap “Start Background Location.” Minimize the app — you should see a persistent notification updating with location data.</li><li>Check Logs: In the console, you’ll see location prints. If not, check for permission denials.</li><li>Common Issues:</li></ol><ul><li>Build Errors: As in the original query, clear caches with flutter clean and delete android/.gradle.</li><li>Permissions Denied: Ensure “Allow all the time” is selected for location on Android 10+.</li><li>Battery Optimization: If tracking stops, disable battery optimization for the app in settings.</li><li>iOS: Background location requires “Always” permission and background modes enabled.</li></ul><h3>Conclusion</h3><p>You’ve now built a functional background location tracker in Flutter! This setup can be extended for real-world use, like sending data to a server or integrating with maps.</p><p>Remember, location tracking raises privacy concerns — always inform users and comply with regulations like GDPR. For production, add error handling, data persistence, and user consent flows.</p><p>If you run into issues, check the package docs or share logs in the comments. Happy coding! 🚀</p><p><em>Code available on GitHub: </em><a href="https://github.com/karttiktungenwar/live_tracking">https://github.com/karttiktungenwar/live_tracking</a></p><h3>Additional Steps for iOS Background Location Tracking in Flutter</h3><p>The original Medium article focuses on implementing background location tracking in Flutter, primarily for Android. To extend it to iOS, you’ll need to handle platform-specific configurations, as iOS has stricter privacy and permission requirements. Below, I’ll outline the key changes and additions for iOS, assuming you’re using a package like geolocator (as mentioned in the article). These steps build on the existing guide—integrate them after the general Flutter setup.</p><h4>1. Update iOS Permissions in Info.plist</h4><p>iOS requires explicit permission declarations for location access. Add these keys to your ios/Runner/Info.plist file (open it in Xcode or a text editor).</p><pre>&lt;key&gt;NSLocationWhenInUseUsageDescription&lt;/key&gt;<br>&lt;string&gt;This app needs access to location to track your position in the background.&lt;/string&gt;<br>&lt;key&gt;NSLocationAlwaysAndWhenInUseUsageDescription&lt;/key&gt;<br>&lt;string&gt;This app needs always access to location for continuous tracking.&lt;/string&gt;<br>&lt;key&gt;NSLocationAlwaysUsageDescription&lt;/key&gt;<br>&lt;string&gt;This app needs always access to location for background tracking.&lt;/string&gt;</pre><ul><li>Why? iOS prompts users for permission based on these descriptions. “Always” permission is crucial for background tracking, but it requires user approval and may trigger additional prompts.</li></ul><h4>2. Enable Background Modes in Xcode</h4><p>Background location tracking on iOS requires enabling specific capabilities.</p><ul><li>Open your project in Xcode (from ios/Runner.xcworkspace).</li><li>Select the Runner target &gt; Signing &amp; Capabilities tab.</li><li>Click the “+” button to add a capability, then choose “Background Modes”.</li><li>Check the box for “Location updates” (and optionally “Background fetch” if needed for periodic tasks).</li><li>Why? This allows the app to run location services in the background without being suspended. Without this, iOS will kill the app after a short time.</li></ul><h4>3. Modify Flutter Code for iOS-Specific Handling</h4><p>In your Dart code (e.g., the service or main file from the article), add iOS-specific logic to request permissions and handle background behavior. Use the geolocator package&#39;s platform checks.</p><pre>import &#39;package:geolocator/geolocator.dart&#39;;<br>import &#39;dart:io&#39; show Platform;<br><br>// In your location service initialization<br>Future&lt;void&gt; initializeLocationService() async {<br>  LocationPermission permission = await Geolocator.checkPermission();<br>  if (permission == LocationPermission.denied) {<br>    permission = await Geolocator.requestPermission();<br>    if (permission == LocationPermission.denied) {<br>      // Handle denial (e.g., show a dialog)<br>      return;<br>    }<br>  }<br><br>  if (permission == LocationPermission.deniedForever) {<br>    // Handle permanent denial<br>    return;<br>  }<br><br>  // For iOS, ensure &quot;Always&quot; permission for background<br>  if (Platform.isIOS) {<br>    if (permission != LocationPermission.always) {<br>      permission = await Geolocator.requestPermission();<br>      if (permission != LocationPermission.always) {<br>        // Inform user they need to enable it in settings<br>        return;<br>      }<br>    }<br>  }<br><br>  // Proceed with location settings (from the original article)<br>  LocationSettings locationSettings = LocationSettings(<br>    accuracy: LocationAccuracy.high,<br>    distanceFilter: 100, // Adjust as needed<br>  );<br><br>  Geolocator.getPositionStream(locationSettings: locationSettings)<br>      .listen((Position position) {<br>    // Handle position updates (e.g., send to server)<br>  });<br>}</pre><ul><li>Why? iOS requires “Always” permission for true background tracking (even when the app is killed). The code checks the platform and requests it explicitly. If denied, guide users to Settings &gt; Privacy &gt; Location Services.</li></ul><h4>4. Handle iOS Background Execution Limits</h4><p>iOS limits background execution time. To keep tracking alive:</p><ul><li>Use a background task (via flutter_background_service or similar) and periodically update location.</li><li>For long-term tracking, consider using significant location changes (less accurate but battery-efficient) by setting LocationSettings with distanceFilter to a higher value (e.g., 500 meters).</li><li>Test on a real device, as simulators don’t fully emulate background behavior.</li><li>Why? iOS suspends apps after ~30 seconds in the background unless using approved modes. This ensures compliance and prevents app termination.</li></ul><h4>5. Testing and Debugging on iOS</h4><ul><li>Run on a physical iOS device (simulators don’t support background location).</li><li>Use Xcode’s console for logs: Add print statements in your Dart code and check via flutter logs.</li><li>Test by putting the app in the background (home button) and monitoring location updates.</li><li>Common issues: Permission denials — verify in Settings. If tracking stops, check for iOS killing the process (use tools like Instruments to profile).</li></ul><h4>Additional Notes</h4><ul><li>Battery and Privacy Considerations: iOS users are sensitive to battery drain and privacy. Clearly explain in your app why background tracking is needed, and provide an opt-out.</li><li>Package Versions: Ensure geolocator: ^9.0.0 or later for better iOS support. Update your pubspec.yaml if needed.</li><li>Legal/Compliance: For production apps, review Apple’s App Store guidelines on location services to avoid rejection.</li><li>If you’re using a different package (e.g., location), adapt these steps accordingly—most follow similar patterns.</li></ul><p>This should integrate seamlessly with the Android steps in the original article. If you encounter specific errors or need code for a different package, provide more details!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac3d6f5fb92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>