<?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 Naufal Prakoso on Medium]]></title>
        <description><![CDATA[Stories by Naufal Prakoso on Medium]]></description>
        <link>https://medium.com/@naufalprakoso24?source=rss-3294105e8e7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D4T_BDn9zAimhDUZEh7FSg@2x.jpeg</url>
            <title>Stories by Naufal Prakoso on Medium</title>
            <link>https://medium.com/@naufalprakoso24?source=rss-3294105e8e7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:18:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naufalprakoso24/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[From Firebase Storage to Bunny.net: How I Cut My Storage Costs by 85%]]></title>
            <link>https://medium.com/@naufalprakoso24/from-firebase-storage-to-bunny-net-how-i-cut-my-storage-costs-by-85-ac4d167b9fac?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac4d167b9fac</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[bunny-net]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firebase-storage]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 00:02:25 GMT</pubDate>
            <atom:updated>2025-12-26T00:02:25.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUGDZVJErQkxB0joKifo3g.png" /></figure><p>When Firebase announced they’re requiring the Blaze plan for Cloud Storage in October 2024, I knew it was time to reconsider my options. Sure, there’s still an “Always Free” tier, but now you’re forced to add a credit card and risk unexpected charges if you accidentally exceed limits.</p><p>My React web app serves about 1,000 daily active users. While my storage usage stayed within Firebase’s free tier (around 65GB storage, 150GB bandwidth/month), the mandatory billing setup felt like a ticking time bomb. One traffic spike, one forgotten cleanup script, and suddenly I’m paying.</p><p>After some research, I discovered Bunny.net, a CDN and storage provider with transparent, predictable pricing. I now pay <strong>$0.76/month</strong> with zero risk of surprise bills. Here’s how I made the switch.</p><h3>The Breaking Point</h3><p>In October 2024, Firebase made a significant change: <strong>all projects using Cloud Storage must upgrade to the Blaze (pay-as-you-go) plan</strong>. Even if your usage stays within the “Always Free” tier.</p><p>This means:</p><ul><li>You’re <strong>required</strong> to add a credit card</li><li>You’re exposed to potential overage charges</li><li>One mistake (a viral post, a bot attack, forgotten files) = unexpected bill</li></ul><p>My app was comfortably within the free tier limits:</p><ul><li>~65GB of storage (free tier: 5GB, so I was already paying)</li><li>~150GB of monthly bandwidth</li><li>Mostly user-generated images and documents</li></ul><p>The Firebase cost wasn’t breaking the bank at around <strong>$8–10/month</strong>, but the <strong>unpredictability</strong> bothered me. I’d rather pay a small, fixed amount than worry about surprise charges.</p><h3>Why Bunny.net?</h3><p>I stumbled upon Bunny.net while looking for alternatives with more transparent pricing. Their model is simple:</p><ul><li>$0.01/GB for storage (HDD tier)</li><li>$0.01–0.03/GB for bandwidth (depending on region)</li><li><strong>No surprise fees, no mandatory credit cards for basic usage</strong></li></ul><p>Quick math: my usage would cost around <strong>$0.65–0.80/month</strong>. More importantly, it’s predictable.</p><p>But price wasn’t everything. What I really needed was:</p><ul><li><strong>Predictable costs</strong>, no risk of surprise bills</li><li>Comparable upload/download speeds</li><li>Global CDN distribution</li><li>Simple API integration</li><li>Migration path that wouldn’t break my production app</li></ul><p>Bunny.net checked all boxes. Plus, I could sleep better knowing my costs were capped.</p><h3>The Migration Strategy</h3><p>I wasn’t about to take down my production app for a storage migration. Here’s the approach I took:</p><h3>Phase 1: Setup &amp; Parallel Running (Week 1)</h3><p>First, I set up Bunny Storage and created a storage zone. Their dashboard is refreshingly simple compared to Firebase Console.</p><pre>// Added Bunny.net config alongside Firebase<br>const bunnyConfig = {<br>  storageZoneName: &#39;my-app-storage&#39;,<br>  apiKey: process.env.BUNNY_API_KEY,<br>  cdnUrl: &#39;https://my-app.b-cdn.net&#39;<br>};</pre><p>I modified my upload function to write to both Firebase and Bunny simultaneously:</p><pre>async function uploadFile(file) {<br>  const fileName = `${Date.now()}-${file.name}`;<br>  <br>  // Upload to both services<br>  const [firebaseUrl, bunnyUrl] = await Promise.all([<br>    uploadToFirebase(file, fileName),<br>    uploadToBunny(file, fileName)<br>  ]);<br>  <br>  // Save both URLs in database for fallback<br>  await db.collection(&#39;files&#39;).add({<br>    fileName,<br>    firebaseUrl,<br>    bunnyUrl,<br>    primarySource: &#39;bunny&#39;, // Start using Bunny for new uploads<br>    createdAt: new Date()<br>  });<br>  <br>  return bunnyUrl;<br>}</pre><h3>Phase 2: Migrating Existing Files (Week 2–3)</h3><p>This was the tedious part. I wrote a Node.js script to migrate existing files:</p><pre>const admin = require(&#39;firebase-admin&#39;);<br>const axios = require(&#39;axios&#39;);<br><br>async function migrateFiles() {<br>  const bucket = admin.storage().bucket();<br>  const [files] = await bucket.getFiles();<br>  <br>  for (const file of files) {<br>    try {<br>      // Download from Firebase<br>      const [buffer] = await file.download();<br>      <br>      // Upload to Bunny<br>      await axios.put(<br>        `https://storage.bunnycdn.com/${STORAGE_ZONE}/${file.name}`,<br>        buffer,<br>        {<br>          headers: {<br>            &#39;AccessKey&#39;: BUNNY_API_KEY,<br>            &#39;Content-Type&#39;: file.metadata.contentType<br>          }<br>        }<br>      );<br>      <br>      // Update database with new URL<br>      await updateFileUrl(file.name);<br>      <br>      console.log(`Migrated: ${file.name}`);<br>    } catch (error) {<br>      console.error(`Failed to migrate ${file.name}:`, error);<br>      // Log failures for manual retry<br>    }<br>  }<br>}</pre><p>I ran this script during off peak hours, migrating about 50GB per night to avoid hitting rate limits.</p><h3>Phase 3: URL Replacement (Week 4)</h3><p>The tricky part was updating all references. My database had Bunny URLs for new files, but my React app still had Firebase URLs hardcoded in some places.</p><pre>// Old way<br>const imageUrl = `https://firebasestorage.googleapis.com/...`;<br><br>// New way - centralized URL generation<br>function getFileUrl(fileName) {<br>  return `${process.env.REACT_APP_CDN_URL}/${fileName}`;<br>}</pre><p>I did a careful find and replace across my codebase, then tested extensively.</p><h3>Phase 4: Cutover (Week 5)</h3><p>After verifying everything worked on staging:</p><ol><li>Updated environment variables to point to Bunny CDN</li><li>Deployed to production</li><li>Monitored for 48 hours</li><li>Kept Firebase as backup for another week</li></ol><p>No downtime, no broken images. Success.</p><h3>Unexpected Benefits</h3><p>Beyond cost savings, I discovered some nice perks:</p><p><strong>1. Better Performance (Subjectively)</strong> Bunny’s CDN seemed slightly faster for my Southeast Asian users. Firebase CDN is excellent, but Bunny’s edge network is specifically optimized for static content delivery.</p><p><strong>2. Simpler API</strong> Bunny’s REST API is straightforward. No complex SDK initialization, just HTTP requests:</p><pre>// Upload is just a PUT request<br>await fetch(`https://storage.bunnycdn.com/${zone}/${filename}`, {<br>  method: &#39;PUT&#39;,<br>  headers: { &#39;AccessKey&#39;: apiKey },<br>  body: fileBuffer<br>});</pre><p><strong>3. Better Analytics</strong> Bunny’s dashboard shows bandwidth usage by country, popular files, and cache hit rates, useful data I didn’t have with Firebase.</p><p><strong>4. Purge Cache Control</strong> I can now purge specific files from CDN cache instantly via API. Great for when users update profile pictures.</p><h3>Challenges &amp; Gotchas</h3><p>Not everything was smooth:</p><p><strong>CORS Configuration</strong> I had to set up CORS properly on Bunny Storage. Initially forgot this and spent an hour debugging 403 errors.</p><p><strong>Authentication Complexity</strong> Firebase Storage had built in security rules. With Bunny, I had to implement signed URLs for private files:</p><pre>function generateSignedUrl(fileName, expiresIn = 3600) {<br>  const expires = Math.floor(Date.now() / 1000) + expiresIn;<br>  const token = crypto<br>    .createHash(&#39;sha256&#39;)<br>    .update(`${SECURITY_KEY}${fileName}${expires}`)<br>    .digest(&#39;hex&#39;);<br>    <br>  return `${CDN_URL}/${fileName}?token=${token}&amp;expires=${expires}`;<br>}</pre><p><strong>No Built in Image Optimization</strong> Firebase Storage integrates nicely with Cloud Functions for image resizing. With Bunny, I had to handle this differently, I ended up using Bunny’s image processing features (Bunny Optimizer) which actually worked great.</p><h3>The Result</h3><p>Three months in, here’s my current situation:</p><p><strong>Bunny.net:</strong></p><ul><li>Storage (68GB): ~$0.68</li><li>Bandwidth (155GB): ~$0.08</li><li><strong>Total: $0.76/month</strong></li><li><strong>Predictable, capped cost</strong></li></ul><p><strong>Firebase (keeping for auth &amp; database):</strong></p><ul><li>Auth + Firestore: ~$5–8/month (still on free tier mostly)</li><li><strong>Storage: $0</strong> (completely migrated off)</li></ul><p>I’m saving about <strong>$8–9/month</strong> or <strong>$96–108/year</strong>. But more importantly, I eliminated the risk of unexpected charges. No more checking my Firebase dashboard nervously after a traffic spike.</p><h3>Should You Migrate Too?</h3><p>The decision is different now that Firebase requires the Blaze plan for Storage:</p><p><strong>Stick with Firebase if:</strong></p><ul><li>You heavily use Firebase ecosystem (Auth, Firestore, Functions integration) and value tight integration</li><li>You don’t mind adding a credit card and monitoring usage closely</li><li>The convenience of Firebase’s all-in-one platform outweighs cost concerns</li><li>You’re confident your usage patterns are stable and predictable</li></ul><p><strong>Consider Bunny.net (or alternatives) if:</strong></p><ul><li>You want <strong>predictable costs</strong> without surprise bills</li><li>You’re uncomfortable with mandatory credit card requirements for “free” tier</li><li>You’re willing to spend a bit more time on initial setup for long-term savings</li><li>You value peace of mind over tight ecosystem integration</li><li>You prefer to pay only for what you actually use, with transparent pricing</li></ul><p>The mandatory Blaze plan changed the equation. It’s no longer just about cost, it’s about <strong>control and predictability</strong>.</p><h3>Final Thoughts</h3><p>This migration took about 5 weeks of part-time work. The annual savings ($96–108) might seem modest, but the real win is <strong>predictability</strong>.</p><p>With Firebase’s mandatory Blaze plan, you’re one mistake away from an unexpected bill. A bot scraping your images, a viral post, or forgetting to delete old files — any of these could spike your costs overnight.</p><p>With Bunny.net, I know exactly what I’ll pay. $0.76/month. Every month. No surprises.</p><p>If you’re facing similar concerns about Firebase’s new requirements, I’d encourage you to explore alternatives. Bunny.net worked great for me, but Cloudflare R2, Backblaze B2, or Wasabi are also worth considering.</p><p>The key lesson: <strong>sometimes the “free” option isn’t really free</strong>, especially when it comes with mandatory credit cards and unpredictable billing.</p><p><strong>Have questions about the migration process?</strong> Drop them in the comments. I’m happy to share more technical details or help troubleshoot if you’re planning a similar move.</p><p><em>Now sleeping better knowing my storage costs are capped at $0.76/month. ☕</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac4d167b9fac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Compose Multiplatform Project Will Break Without expect/actual]]></title>
            <link>https://medium.com/@naufalprakoso24/why-your-compose-multiplatform-project-will-break-without-expect-actual-9662371e22a0?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9662371e22a0</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 03:07:31 GMT</pubDate>
            <atom:updated>2025-09-21T03:07:31.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1W3sjJX3zFKtgPwScesng.png" /></figure><p>Kotlin Multiplatform sounds magical, share once, run everywhere. Write your business logic in Kotlin, sprinkle some Compose UI on top, and voilà! Your app runs seamlessly on Android, iOS, desktop, and web.</p><p>But here’s the harsh reality: <strong>what happens when your code needs platform specific logic?</strong></p><p>Picture this: You’re building a file manager app. On Android, you access the file system through Context.getFilesDir(). On iOS, you use NSDocumentDirectory. On desktop, it&#39;s System.getProperty(&quot;user.home&quot;). Each platform has its own API, its own way of doing things.</p><p>Without a proper bridge between your shared code and platform specific implementations, your beautiful Compose Multiplatform project will simply <strong>fall apart</strong>.</p><p><em>That’s where expect/actual comes to the rescue.</em></p><h3>What is expect/actual? The Foundation You Can’t Ignore</h3><p>Think of expect/actual as a contract system in Kotlin Multiplatform. The expect keyword is your declaration, a promise that says &quot;I need this functionality, but I don&#39;t know how each platform will implement it.&quot; The actual keyword is the implementation, the platform specific code that fulfills that promise.</p><p>This isn’t just a nice to have feature. <strong>It’s the foundation</strong> that makes true multiplatform development possible.</p><p>Here’s the simplest example:</p><pre>// commonMain/Platform.kt<br>expect fun getPlatformName(): String<br><br>// androidMain/Platform.android.kt  <br>actual fun getPlatformName(): String = &quot;Android&quot;<br><br>// iosMain/Platform.ios.kt<br>actual fun getPlatformName(): String = &quot;iOS&quot;</pre><h3>Why This Matters for Compose Multiplatform</h3><p>Compose Multiplatform excels at sharing UI code, but your app doesn’t live in a UI bubble. Real applications need to access device cameras and sensors, read and write files to local storage, handle platform specific permissions, integrate with native APIs, and manage platform specific configurations.</p><p><strong>Without expect/actual, you’d be forced into painful alternatives.</strong> You could duplicate everything and write separate apps for each platform, goodbye code sharing! Or compromise functionality by only using features available on all platforms. Some developers try to hack around limitations with fragile workarounds that break with updates.</p><p>expect/actual eliminates these compromises. It’s the official Kotlin Multiplatform solution that lets you write clean, maintainable code while accessing the full power of each platform.</p><h3>Real World Example: Platform Detection</h3><p>Let’s build something practical. Here’s how to create a platform detector that works across all platforms:</p><pre>// commonMain/kotlin/Platform.kt<br>expect fun getPlatformName(): String<br>expect fun getPlatformVersion(): String<br><br>// commonMain/kotlin/PlatformInfo.kt<br>data class PlatformInfo(<br>    val name: String,<br>    val version: String,<br>    val isAndroid: Boolean = name == &quot;Android&quot;,<br>    val isIOS: Boolean = name == &quot;iOS&quot;<br>)<br>fun currentPlatform() = PlatformInfo(<br>    name = getPlatformName(),<br>    version = getPlatformVersion()<br>)</pre><p>Now the platform specific implementations:</p><pre>// androidMain/kotlin/Platform.android.kt<br>import android.os.Build<br><br>actual fun getPlatformName(): String = &quot;Android&quot;<br>actual fun getPlatformVersion(): String = &quot;${Build.VERSION.SDK_INT}&quot;</pre><pre>// iosMain/kotlin/Platform.ios.kt<br>import platform.UIKit.UIDevice<br><br>actual fun getPlatformName(): String = &quot;iOS&quot;<br>actual fun getPlatformVersion(): String = UIDevice.currentDevice.systemVersion</pre><p>Use it in your Compose UI:</p><pre>@Composable<br>fun PlatformScreen() {<br>    val platform = remember { currentPlatform() }<br>    <br>    Column(<br>        modifier = Modifier.fillMaxSize().padding(16.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(<br>            text = &quot;Running on ${platform.name}&quot;,<br>            style = MaterialTheme.typography.headlineMedium<br>        )<br>        Text(<br>            text = &quot;Version: ${platform.version}&quot;,<br>            style = MaterialTheme.typography.bodyLarge<br>        )<br>        <br>        if (platform.isAndroid) {<br>            Text(&quot;Android specific features available!&quot;)<br>        } else if (platform.isIOS) {<br>            Text(&quot;iOS specific features available!&quot;)<br>        }<br>    }<br>}</pre><h3>Advanced Example: Camera Access</h3><p>Here’s where expect/actual really shines. Let’s implement camera functionality that works properly across platforms:</p><pre>// commonMain/kotlin/Camera.kt<br>expect class CameraManager() {<br>    suspend fun requestPermission(): Boolean<br>    suspend fun capturePhoto(): ByteArray?<br>    fun isAvailable(): Boolean<br>}<br><br>// commonMain/kotlin/CameraRepository.kt<br>class CameraRepository {<br>    private val cameraManager = CameraManager()<br>    <br>    suspend fun takePhoto(): Result&lt;ByteArray&gt; {<br>        return try {<br>            if (!cameraManager.isAvailable()) {<br>                return Result.failure(Exception(&quot;Camera not available&quot;))<br>            }<br>            <br>            val hasPermission = cameraManager.requestPermission()<br>            if (!hasPermission) {<br>                return Result.failure(Exception(&quot;Camera permission denied&quot;))<br>            }<br>            <br>            val photoData = cameraManager.capturePhoto()<br>            if (photoData != null) {<br>                Result.success(photoData)<br>            } else {<br>                Result.failure(Exception(&quot;Failed to capture photo&quot;))<br>            }<br>        } catch (e: Exception) {<br>            Result.failure(e)<br>        }<br>    }<br>}</pre><p>Android implementation:</p><pre>// androidMain/kotlin/Camera.android.kt<br>import android.Manifest<br>import android.content.Context<br>import android.content.pm.PackageManager<br>import androidx.core.content.ContextCompat<br>import androidx.camera.core.*<br>import androidx.camera.lifecycle.ProcessCameraProvider<br>import androidx.lifecycle.LifecycleOwner<br>import java.io.File<br>import java.util.concurrent.ExecutorService<br>import java.util.concurrent.Executors<br>import kotlinx.coroutines.suspendCancellableCoroutine<br>import kotlin.coroutines.resume<br><br>actual class CameraManager {<br>    private lateinit var context: Context<br>    private lateinit var lifecycleOwner: LifecycleOwner<br>    private var cameraExecutor: ExecutorService = Executors.newSingleThreadExecutor()<br>    <br>    fun initialize(context: Context, lifecycleOwner: LifecycleOwner) {<br>        this.context = context<br>        this.lifecycleOwner = lifecycleOwner<br>    }<br>    <br>    actual suspend fun requestPermission(): Boolean {<br>        return ContextCompat.checkSelfPermission(<br>            context,<br>            Manifest.permission.CAMERA<br>        ) == PackageManager.PERMISSION_GRANTED<br>    }<br>    <br>    actual suspend fun capturePhoto(): ByteArray? {<br>        return suspendCancellableCoroutine { continuation -&gt;<br>            val imageCapture = ImageCapture.Builder().build()<br>            <br>            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(<br>                File(context.cacheDir, &quot;temp_photo_${System.currentTimeMillis()}.jpg&quot;)<br>            ).build()<br>            <br>            imageCapture.takePicture(<br>                outputFileOptions,<br>                ContextCompat.getMainExecutor(context),<br>                object : ImageCapture.OnImageSavedCallback {<br>                    override fun onImageSaved(output: ImageCapture.OutputFileResults) {<br>                        try {<br>                            val file = output.savedUri?.path?.let { File(it) }<br>                            val byteArray = file?.readBytes()<br>                            continuation.resume(byteArray)<br>                            file?.delete()<br>                        } catch (e: Exception) {<br>                            continuation.resume(null)<br>                        }<br>                    }<br>                    <br>                    override fun onError(exception: ImageCaptureException) {<br>                        continuation.resume(null)<br>                    }<br>                }<br>            )<br>            <br>            val cameraProviderFuture = ProcessCameraProvider.getInstance(context)<br>            cameraProviderFuture.addListener({<br>                val cameraProvider = cameraProviderFuture.get()<br>                val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA<br>                <br>                try {<br>                    cameraProvider.unbindAll()<br>                    cameraProvider.bindToLifecycle(<br>                        lifecycleOwner,<br>                        cameraSelector,<br>                        imageCapture<br>                    )<br>                } catch (e: Exception) {<br>                    continuation.resume(null)<br>                }<br>            }, ContextCompat.getMainExecutor(context))<br>        }<br>    }<br>    <br>    actual fun isAvailable(): Boolean {<br>        return context.packageManager.hasSystemFeature(<br>            PackageManager.FEATURE_CAMERA_ANY<br>        )<br>    }<br>}</pre><p>iOS implementation:</p><pre>// iosMain/kotlin/Camera.ios.kt<br>import platform.AVFoundation.*<br>import platform.UIKit.*<br>import platform.Foundation.*<br>import kotlinx.coroutines.suspendCancellableCoroutine<br>import kotlin.coroutines.resume<br>import kotlinx.cinterop.*<br><br>actual class CameraManager {<br>    <br>    actual suspend fun requestPermission(): Boolean {<br>        return suspendCancellableCoroutine { continuation -&gt;<br>            AVCaptureDevice.requestAccessForMediaType(<br>                AVMediaTypeVideo<br>            ) { granted -&gt;<br>                continuation.resume(granted)<br>            }<br>        }<br>    }<br>    <br>    @OptIn(ExperimentalForeignApi::class)<br>    actual suspend fun capturePhoto(): ByteArray? {<br>        return suspendCancellableCoroutine { continuation -&gt;<br>            val imagePicker = UIImagePickerController()<br>            <br>            val delegate = object : NSObject(), UIImagePickerControllerDelegateProtocol, UINavigationControllerDelegateProtocol {<br>                override fun imagePickerController(<br>                    picker: UIImagePickerController,<br>                    didFinishPickingMediaWithInfo: Map&lt;Any?, *&gt;<br>                ) {<br>                    val originalImage = didFinishPickingMediaWithInfo[UIImagePickerControllerOriginalImage] as? UIImage<br>                    <br>                    originalImage?.let { image -&gt;<br>                        val imageData = UIImageJPEGRepresentation(image, 0.8)<br>                        val byteArray = imageData?.let { data -&gt;<br>                            ByteArray(data.length.toInt()).apply {<br>                                data.getBytes(this.refTo(0), data.length.toULong())<br>                            }<br>                        }<br>                        continuation.resume(byteArray)<br>                    } ?: continuation.resume(null)<br>                    <br>                    picker.dismissViewControllerAnimated(true, null)<br>                }<br>                <br>                override fun imagePickerControllerDidCancel(picker: UIImagePickerController) {<br>                    continuation.resume(null)<br>                    picker.dismissViewControllerAnimated(true, null)<br>                }<br>            }<br>            <br>            imagePicker.sourceType = UIImagePickerControllerSourceType.UIImagePickerControllerSourceTypeCamera<br>            imagePicker.allowsEditing = false<br>            imagePicker.delegate = delegate<br>            <br>            val rootViewController = UIApplication.sharedApplication.keyWindow?.rootViewController<br>            rootViewController?.presentViewController(imagePicker, animated = true, completion = null)<br>            <br>            continuation.invokeOnCancellation {<br>                imagePicker.delegate = null<br>            }<br>        }<br>    }<br>    <br>    actual fun isAvailable(): Boolean {<br>        return UIImagePickerController.isSourceTypeAvailable(<br>            UIImagePickerControllerSourceType.UIImagePickerControllerSourceTypeCamera<br>        )<br>    }<br>}</pre><p>Use it in your Compose UI:</p><pre>@Composable<br>fun CameraScreen() {<br>    val cameraRepository = remember { CameraRepository() }<br>    var photoResult by remember { mutableStateOf&lt;Result&lt;ByteArray&gt;?&gt;(null) }<br>    var isLoading by remember { mutableStateOf(false) }<br>    val coroutineScope = rememberCoroutineScope()<br>    <br>    Column(<br>        modifier = Modifier.fillMaxSize().padding(16.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Button(<br>            onClick = {<br>                isLoading = true<br>                coroutineScope.launch {<br>                    photoResult = cameraRepository.takePhoto()<br>                    isLoading = false<br>                }<br>            },<br>            enabled = !isLoading<br>        ) {<br>            if (isLoading) {<br>                CircularProgressIndicator(<br>                    modifier = Modifier.size(16.dp),<br>                    color = MaterialTheme.colorScheme.onPrimary<br>                )<br>                Spacer(modifier = Modifier.width(8.dp))<br>            }<br>            Text(if (isLoading) &quot;Capturing...&quot; else &quot;Take Photo&quot;)<br>        }<br>        <br>        Spacer(modifier = Modifier.height(16.dp))<br>        <br>        photoResult?.let { result -&gt;<br>            when {<br>                result.isSuccess -&gt; {<br>                    Card(<br>                        modifier = Modifier.fillMaxWidth(),<br>                        colors = CardDefaults.cardColors(<br>                            containerColor = MaterialTheme.colorScheme.primaryContainer<br>                        )<br>                    ) {<br>                        Text(<br>                            text = &quot;Photo captured successfully!&quot;,<br>                            modifier = Modifier.padding(16.dp),<br>                            color = MaterialTheme.colorScheme.onPrimaryContainer<br>                        )<br>                    }<br>                }<br>                result.isFailure -&gt; {<br>                    Card(<br>                        modifier = Modifier.fillMaxWidth(),<br>                        colors = CardDefaults.cardColors(<br>                            containerColor = MaterialTheme.colorScheme.errorContainer<br>                        )<br>                    ) {<br>                        Text(<br>                            text = &quot;Error: ${result.exceptionOrNull()?.message}&quot;,<br>                            modifier = Modifier.padding(16.dp),<br>                            color = MaterialTheme.colorScheme.onErrorContainer<br>                        )<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Common Mistakes That Break Projects</h3><p><strong>Wrong Module Placement</strong></p><p>Putting actual implementations in the wrong module is a classic mistake. The actual keyword must go in platform specific modules, never in commonMain.</p><pre>// Wrong approach<br>// commonMain/Platform.kt<br>actual fun getPlatformName() = &quot;Common&quot; // This will fail!<br><br>// Correct approach<br>// androidMain/Platform.android.kt<br>actual fun getPlatformName() = &quot;Android&quot;</pre><p><strong>Inconsistent Signatures</strong></p><p>All actual implementations must have identical signatures to their expect declaration. Adding or removing parameters will cause compilation errors.</p><pre>// Wrong approach<br>// commonMain<br>expect fun saveFile(content: String): Boolean<br>// androidMain  <br>actual fun saveFile(content: String, filename: String): Boolean // Extra parameter!<br><br>// Correct approach<br>// commonMain<br>expect fun saveFile(content: String, filename: String): Boolean<br>// androidMain<br>actual fun saveFile(content: String, filename: String): Boolean</pre><p><strong>Overusing expect/actual</strong></p><p>Not everything needs platform specific implementation. Many utilities can be shared across platforms using existing multiplatform libraries.</p><pre>// Unnecessary expect/actual<br>expect fun formatCurrency(amount: Double): String<br><br>// Better approach using shared libraries<br>// commonMain<br>fun formatCurrency(amount: Double): String {<br>    return NumberFormat.getCurrencyInstance().format(amount)<br>}</pre><h3>Best Practices for Success</h3><p><strong>Keep Common Code Maximized</strong></p><p>Put as much logic as possible in commonMain. Use expect/actual only when you genuinely need platform specific behavior. Consider existing shared libraries before writing your own expect/actual implementations.</p><p><strong>Document Platform Differences</strong></p><p>Clear documentation helps other developers understand what each platform does differently.</p><pre>/**<br> * Saves file to platform specific location<br> * Android: Uses internal storage<br> * iOS: Uses Documents directory  <br> * Desktop: Uses user home directory<br> */<br>expect suspend fun saveFile(content: String, filename: String): Boolean</pre><p><strong>Maintain Consistent Behavior</strong></p><p>All actual implementations should behave similarly from the caller&#39;s perspective. Handle errors consistently across platforms, return the same data types and formats, and ensure the user experience feels uniform regardless of platform.</p><p><strong>Test Each Platform</strong></p><p>Write tests for both common and platform specific code. Verify behavior is consistent across platforms and test error scenarios on all platforms. Don’t assume that working on one platform means it works everywhere.</p><h3>The Bottom Line</h3><p>Here’s the truth: <strong>Your Compose Multiplatform project can literally break without expect/actual.</strong></p><p>Try to access a camera without it? Compilation error. Need to read platform specific files? Runtime crash. Want to integrate with native APIs? Dead end.</p><p>expect/actual isn’t just a feature, it’s the bridge that makes true multiplatform development possible. It’s what transforms Kotlin Multiplatform from a promising idea into a production ready solution.</p><p><strong>The sooner you embrace expect/actual, the smoother your multiplatform journey will be.</strong></p><p>Stop fighting against the platform differences. Start leveraging them with expect/actual, and watch your Compose Multiplatform project thrive across every device your users love.</p><p><em>Ready to dive deeper into Compose Multiplatform? Follow me for more practical guides and real world examples that will level up your multiplatform development skills.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9662371e22a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should You Trust Compose Multiplatform with Your Established App?]]></title>
            <link>https://medium.com/@naufalprakoso24/should-you-trust-compose-multiplatform-with-your-established-app-9f921a9a47aa?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f921a9a47aa</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 05:07:48 GMT</pubDate>
            <atom:updated>2025-08-31T05:07:48.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLDrGrh97u10mU5o4ahqhA.png" /></figure><h3>The Million User Reality Check</h3><p>Compose Multiplatform (CMP) promises “one UI codebase” for Android, iOS, desktop, and web. However, when dealing with production applications serving <strong>over 1 million users</strong>, several critical risks emerge that cannot be ignored.</p><p>At this scale, the performance overhead that seems negligible during development becomes amplified, and user expectations shift dramatically. Production apps must deliver consistent performance across hundreds of device models while maintaining platform native user experiences.</p><h3>The Four Critical Risks for Large Scale Production Apps</h3><h3>1. UX Consistency Problems</h3><ul><li><strong>Android users expect Material 3</strong> design language and navigation patterns</li><li><strong>iOS users expect Human Interface Guidelines</strong> compliance and familiar gestures</li><li><strong>CMP cannot deliver 100% compliance</strong> with both platforms simultaneously</li><li>Apps feel “foreign” to users accustomed to polished, platform native applications</li></ul><h3>2. Performance Degradation at Scale</h3><ul><li><strong>CMP rendering engine</strong> is not yet as optimized as native Compose Android or SwiftUI</li><li><strong>Frame drops and UI jank</strong> become immediately visible in user reviews and app store ratings</li><li>Large scale applications with complex data and heavy animations expose performance bottlenecks</li></ul><h3>3. Ecosystem and Maturity Limitations</h3><ul><li><strong>CMP is relatively new</strong> with smaller documentation, libraries, and community support</li><li><strong>For 1+ million user applications</strong>: Stability and long term maintenance take priority over “one codebase” convenience</li><li>Production debugging and optimization tools are less mature compared to native alternatives</li></ul><h3>4. Team and Scalability Challenges</h3><ul><li><strong>Large companies have dedicated Android and iOS teams</strong> with deep platform expertise</li><li><strong>Forcing CMP adoption</strong> reduces team flexibility to leverage platform specific features like Dynamic Island (iOS) or Jetpack Widgets (Android)</li><li>Platform expertise becomes diluted rather than utilized effectively</li></ul><h3>Performance Data Analysis</h3><p><em>Note: Data combines official documentation, open source benchmarking, and industry research</em></p><p><strong>Production Impact (1M+ users):</strong></p><ul><li>CMP overhead: 10–15% performance penalty on mid range devices</li><li>App size increase: 60–80% larger binaries vs native</li><li>Potential user impact: 70,000–105,000 lost users per million from performance issues</li></ul><p><strong>CMP Technical Overhead:</strong></p><pre>Rendering Pipeline: +5.1ms per frame average<br>Memory Usage: +25-50MB baseline overhead<br>Binary Size: +20-35MB per platform</pre><p><strong>KMP Efficiency:</strong></p><pre>Business Logic Overhead: &lt;3% CPU impact  <br>Memory Usage: +2-4MB for shared modules<br>Binary Size: +8-12% increase only</pre><h3>When to Choose What</h3><h3>✅ CMP is Excellent For:</h3><ul><li><strong>MVP and rapid prototyping</strong> when speed to market is critical</li><li><strong>Side projects and internal tools</strong> where development velocity trumps platform perfection</li><li><strong>Early stage startups</strong> needing to validate market fit quickly</li></ul><h3>🚫 Avoid CMP For:</h3><ul><li><strong>Production apps with 1+ million users</strong> where scale demands performance</li><li><strong>Apps requiring platform specific features</strong> and advanced integrations</li><li><strong>Long term commercial products</strong> where stability is business critical</li></ul><h3>Why KMP is the Production Solution</h3><p><strong>Kotlin Multiplatform Mobile (KMP)</strong> provides the optimal approach for million user applications:</p><p><strong>Share Business Logic Only:</strong></p><ul><li>Data models, networking, business rules, repositories</li><li>Keep UI platform native: Jetpack Compose (Android) + SwiftUI (iOS)</li></ul><p><strong>Production Benefits:</strong></p><ul><li>✅ Native performance on both platforms</li><li>✅ Full platform compliance and user experience quality</li><li>✅ iOS developers use iOS tools, Android developers use Android tools</li><li>✅ Access to latest platform features immediately</li></ul><h3>The Production Decision</h3><p>For applications with substantial user bases, <strong>KMP + native UI delivers superior performance, platform compliance, and user experience</strong> compared to CMP.</p><p><strong>The Strategy:</strong></p><ol><li><strong>Share business logic</strong> through KMP for development efficiency</li><li><strong>Keep UI native</strong> for optimal performance and platform compliance</li><li><strong>Maintain team expertise</strong> in platform specific development</li><li><strong>Scale safely</strong> without compromising user experience</li></ol><p><strong>The Bottom Line:</strong> Save CMP for MVPs and prototypes. For production apps serving millions of users, choose KMP for the business logic and native UI for the user experience.</p><p>The technology decisions you make today impact millions of users tomorrow.</p><blockquote>“Users don’t care if you save 30% dev time. They care if the app feels fast, smooth, and native. That’s why in production, consider to choose KMP instead CMP to share what makes sense, the business logic while keeping UI native on each platform.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f921a9a47aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Flutter Apps Are Larger Than You Think (And It’s Not Your Images)]]></title>
            <link>https://medium.com/@naufalprakoso24/why-flutter-apps-are-larger-than-you-think-and-its-not-your-images-248fb3c22158?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/248fb3c22158</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 03:51:50 GMT</pubDate>
            <atom:updated>2025-08-17T03:51:50.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0kjeGu-Xr5t4po_aJVfNQ.png" /></figure><p><em>A deep dive into Flutter’s app size mystery that surprises most developers</em></p><p>Picture this: You’ve just created your first Flutter app. It’s basically empty — just the default counter app with maybe a logo or two. You build the APK, check the file size, and nearly spit out your coffee. <strong>20+ MB for an empty app?</strong></p><p>Your first instinct? “Must be those PNG files I added.” You delete them, rebuild, and… it’s still 18 MB. Welcome to one of Flutter’s most misunderstood aspects: <strong>app size isn’t about your assets — it’s about the engine.</strong></p><h3>The Native App Advantage (And Why It’s Misleading)</h3><p>When you build a native Android app with Kotlin or an iOS app with Swift, you get spoiled by those tiny initial APK/IPA sizes — often just 2–5 MB for a basic app. But here’s the thing: <strong>native apps are essentially freeloaders.</strong></p><p>Think of it this way:</p><ul><li><strong>Native apps</strong>: “Hey Android/iOS, can I borrow your UI toolkit, rendering engine, and text processing? Thanks!”</li><li><strong>Flutter apps</strong>: “Nope, I’ll bring my own chair, table, and entire dining set, thank you very much.”</li></ul><p>Native apps stay small because they rely heavily on the operating system’s built-in libraries. They’re like house guests who travel light because they know the host has everything they need.</p><h3>Forensic Analysis: What’s Actually Inside Your Flutter App</h3><p>Let’s crack open a Flutter APK and see what’s eating up all that space. Run this command on your project:</p><pre>flutter build apk --analyze-size</pre><p>Here’s what you’ll typically find in an empty Flutter app:</p><h3>1. Dart AOT Runtime (~6–8 MB)</h3><p>This is your Dart code compiled to machine code, plus the essential VM components needed to run it. Even an “empty” app has the entire Dart runtime ready to go.</p><h3>2. Skia Rendering Engine (~4–6 MB)</h3><p>Flutter doesn’t use the platform’s native UI components. Instead, it brings Skia — Google’s powerful 2D graphics library — to draw every pixel on screen. This ensures your button looks identical on Android 6 and iOS 16.</p><h3>3. ICU Data (~2–4 MB)</h3><p>International Components for Unicode. This handles text shaping, date formatting, number formatting, and character encoding for every language Flutter might need to support.</p><h3>4. Flutter Framework (~2–3 MB)</h3><p>The actual Flutter widgets, animation systems, gesture recognizers, and all the framework code that makes Flutter… well, Flutter.</p><h3>5. Platform-Specific Code (~1–2 MB)</h3><p>The bridge code that lets Flutter talk to Android/iOS APIs, plus any platform-specific implementations.</p><p>Your actual app code? Maybe 100KB if you’re being verbose.</p><h3>Why Flutter Can’t Just “Use System Libraries”</h3><p>“But wait,” you might ask, “why can’t Flutter just use Android’s built-in rendering like native apps do?”</p><p>The answer lies in Flutter’s core philosophy: <strong>predictable, consistent UI across platforms.</strong></p><h3>The Consistency Problem</h3><p>Android 7’s button doesn’t look like Android 12’s button, which doesn’t look like iOS 16’s button. If Flutter used system UI components, your app would look different on every device. Material Design on Android, Cupertino on iOS, and good luck with that edge case Samsung skin.</p><h3>The Performance Promise</h3><p>By bundling Skia, Flutter can optimize rendering in ways that platform-agnostic UI frameworks can’t. It knows exactly how every pixel will be drawn, enabling smooth 60fps animations and predictable performance.</p><h3>The “Write Once, Run Anywhere” Reality</h3><p>Flutter apps don’t just run on mobile. The same codebase works on web, desktop, and embedded devices. This universality requires bringing your own rendering engine — you can’t rely on system libraries that might not exist.</p><h3>Why Adding Images Barely Moves the Needle</h3><p>Here’s where most developers get confused. You add a 2MB image to your app, and yes, the APK grows by 2MB. But you’re adding 2MB to an <strong>existing 18MB baseline</strong>.</p><p>It’s like worrying about the weight of your luggage when you’re already carrying a bowling ball in your backpack. The bowling ball (Flutter engine) was always there — you just didn’t notice it until you tried to add something else.</p><p>This is why mature Flutter apps with dozens of screens, hundreds of images, and complex logic might only be 25–30MB. The engine size is front-loaded; everything else is incremental.</p><h3>Strategies to Reduce Size (With Realistic Expectations)</h3><p>While you can’t eliminate Flutter’s baseline size, you can optimize it:</p><h3>1. Use App Bundles (AAB)</h3><p>Instead of bundling ARM64, ARMv7, and x86 architectures in one APK, let Google Play Store deliver only what each device needs:</p><pre>flutter build appbundle --target-platform android-arm,android-arm64</pre><p>This can reduce download size by 30–40% for end users.</p><h3>2. Enable R8/ProGuard Shrinking</h3><p>Add this to your android/app/build.gradle:</p><pre>buildTypes {<br>    release {<br>        shrinkResources true<br>        minifyEnabled true<br>        proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>    }<br>}</pre><h3>3. Remove Unused Locales</h3><p>If your app only supports a few languages, exclude ICU data for others:</p><pre>// In your MaterialApp<br>localizationsDelegates: [<br>    GlobalMaterialLocalizations.delegate,<br>    GlobalWidgetsLocalizations.delegate,<br>],<br>supportedLocales: [<br>    Locale(&#39;en&#39;, &#39;US&#39;),<br>    Locale(&#39;es&#39;, &#39;ES&#39;),<br>    // Only the locales you actually need<br>],</pre><h3>4. Tree Shaking (Automatic)</h3><p>Flutter automatically removes unused Dart code in release builds. This is most effective for large codebases with many dependencies.</p><p><strong>Reality check</strong>: These optimizations might save you 20–30% of total size, but you’re still looking at 12–15MB minimum for most Flutter apps.</p><h3>The Size Comparison Reality</h3><p>Let’s be honest about the numbers:</p><p>App Type Empty App Size With Features Native Android (Kotlin) 2–4 MB 8–15 MB Native iOS (Swift) 1–3 MB 6–12 MB Flutter 15–20 MB 25–35 MB React Native 8–12 MB 20–30 MB</p><p>Flutter apps start larger but scale more predictably. A complex native app with animations, networking, and rich UI can easily reach Flutter’s baseline size once you factor in all the libraries you’ll inevitably add.</p><h3>The Trade-off Truth</h3><p>Flutter’s size isn’t a bug — it’s a feature. You’re trading disk space for:</p><ul><li><strong>Predictable UI</strong> across all devices and OS versions</li><li><strong>Consistent performance</strong> regardless of platform</li><li><strong>Single codebase</strong> for multiple platforms</li><li><strong>Rapid development</strong> with hot reload and rich tooling</li><li><strong>Future-proofing</strong> as platforms evolve</li></ul><p>In 2024, when phones have 128GB+ storage and app stores use delta updates, is an extra 10–15MB really a dealbreaker for most users? That’s roughly equivalent to 30 seconds of HD video or a handful of photos.</p><h3>The Bottom Line</h3><p>Your Flutter app is large not because you’re doing something wrong, but because <strong>Flutter brings its own world with it</strong>. It’s less like a traditional app and more like a mini-operating system that happens to run your code.</p><p>This independence comes with a cost in megabytes but pays dividends in consistency, performance, and developer productivity. The question isn’t whether you can make Flutter apps as small as native ones (you can’t), but whether the trade-offs are worth it for your specific use case.</p><p>Next time someone complains about Flutter app sizes, remind them: you’re not just downloading an app — you’re downloading a guarantee that it will look and behave exactly as intended, regardless of what device it’s running on.</p><p><em>What’s your take? Do you prioritize smaller app sizes or consistent cross-platform behavior? Share your thoughts in the comments below.</em></p><p><em>If you found this helpful, consider following me for more deep dives into mobile development mysteries. Got a Flutter performance question? Drop it in the comments — I love solving these puzzles.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=248fb3c22158" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter vs Compose Multiplatform: UI Development for Android and iOS]]></title>
            <link>https://medium.com/@naufalprakoso24/flutter-vs-compose-multiplatform-ui-development-for-android-and-ios-bc6ac14a4090?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc6ac14a4090</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 14:18:29 GMT</pubDate>
            <atom:updated>2025-09-06T00:34:50.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7jTRxBzZY84lMHSxxLKvw.png" /></figure><p><em>A practical comparison of UI development approaches between Flutter and Compose Multiplatform for mobile applications.</em></p><p>The mobile development landscape has evolved dramatically, offering developers powerful frameworks that promise code sharing without sacrificing quality. When building Android and iOS applications, two prominent solutions stand out: Flutter and Compose Multiplatform (CMP).</p><p>Both frameworks offer declarative UI development, but with fundamentally different approaches. Let’s examine how they compare specifically for mobile UI development.</p><h3>The Fundamental Difference</h3><p>Before we explore the UI aspects, it’s crucial to understand the fundamental philosophical differences between these two approaches:</p><p><strong>Flutter</strong> renders UI using its own engine (Skia) across Android and iOS, providing pixel perfect consistency with a single codebase.</p><p><strong>Compose Multiplatform</strong> extends Jetpack Compose to work on both Android and iOS, offering a unified declarative UI approach while maintaining platform native performance characteristics.</p><p>This fundamental difference shapes everything about how you’ll approach UI development in each framework.</p><h3>Android UI Development</h3><h3>Flutter for Android</h3><p>Flutter provides Material Design components out of the box, making Android UI development straightforward:</p><pre>// Flutter Material Design<br>Scaffold(<br>  appBar: AppBar(<br>    title: Text(&#39;Android App&#39;),<br>    backgroundColor: Theme.of(context).primaryColor,<br>  ),<br>  body: Column(<br>    children: [<br>      Card(<br>        child: ListTile(<br>          leading: Icon(Icons.person),<br>          title: Text(&#39;User Profile&#39;),<br>          trailing: Icon(Icons.arrow_forward_ios),<br>        ),<br>      ),<br>      FloatingActionButton(<br>        onPressed: () {},<br>        child: Icon(Icons.add),<br>      ),<br>    ],<br>  ),<br>)</pre><p><strong>Android specific advantages:</strong></p><ul><li>Automatic Material Design theming</li><li>Consistent with Material Design guidelines</li><li>Easy integration with Android system UI</li><li>Supports Android specific features like adaptive icons</li></ul><h3>Android UI Development</h3><h3>Flutter for Android</h3><p>Flutter provides Material Design components out of the box, making Android UI development straightforward:</p><pre>// Flutter Material Design<br>Scaffold(<br>  appBar: AppBar(<br>    title: Text(&#39;Android App&#39;),<br>    backgroundColor: Theme.of(context).primaryColor,<br>  ),<br>  body: Column(<br>    children: [<br>      Card(<br>        child: ListTile(<br>          leading: Icon(Icons.person),<br>          title: Text(&#39;User Profile&#39;),<br>          trailing: Icon(Icons.arrow_forward_ios),<br>        ),<br>      ),<br>      FloatingActionButton(<br>        onPressed: () {},<br>        child: Icon(Icons.add),<br>      ),<br>    ],<br>  ),<br>)</pre><p><strong>Android specific advantages:</strong></p><ul><li>Automatic Material Design theming</li><li>Consistent with Material Design guidelines</li><li>Easy integration with Android system UI</li><li>Supports Android specific features like adaptive icons</li></ul><h3>Compose Multiplatform for Android</h3><p>CMP uses the same Jetpack Compose that Android developers already know:</p><pre>// Jetpack Compose on Android<br>@Composable<br>fun AndroidScreen(userRepository: UserRepository) {<br>    val users by userRepository.getUsers().collectAsState()<br>    <br>    Scaffold(<br>        topBar = {<br>            TopAppBar(<br>                title = { Text(&quot;Android App&quot;) },<br>                backgroundColor = MaterialTheme.colors.primary<br>            )<br>        },<br>        floatingActionButton = {<br>            FloatingActionButton(<br>                onClick = { /* handle click */ }<br>            ) {<br>                Icon(Icons.Default.Add, contentDescription = &quot;Add&quot;)<br>            }<br>        }<br>    ) { paddingValues -&gt;<br>        LazyColumn(<br>            modifier = Modifier.padding(paddingValues)<br>        ) {<br>            items(users) { user -&gt;<br>                Card(modifier = Modifier.padding(8.dp)) {<br>                    ListItem(<br>                        headlineContent = { Text(user.name) },<br>                        leadingContent = { <br>                            Icon(Icons.Default.Person, null) <br>                        }<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Android specific advantages:</strong></p><ul><li>100% native Jetpack Compose performance</li><li>Full access to latest Android APIs</li><li>Seamless integration with existing Android apps</li><li>Better memory management for Android</li><li>Native Android navigation patterns</li></ul><h3>iOS UI Development</h3><h3>Flutter for iOS</h3><p>Flutter provides Cupertino widgets that mimic iOS design patterns:</p><pre>// Flutter Cupertino Design<br>CupertinoPageScaffold(<br>  navigationBar: CupertinoNavigationBar(<br>    middle: Text(&#39;iOS App&#39;),<br>  ),<br>  child: SafeArea(<br>    child: Column(<br>      children: [<br>        CupertinoListSection.insetGrouped(<br>          children: [<br>            CupertinoListTile(<br>              leading: Icon(CupertinoIcons.person),<br>              title: Text(&#39;User Profile&#39;),<br>              trailing: CupertinoListTileChevron(),<br>              onTap: () {},<br>            ),<br>          ],<br>        ),<br>        CupertinoButton.filled(<br>          child: Text(&#39;Add Item&#39;),<br>          onPressed: () {},<br>        ),<br>      ],<br>    ),<br>  ),<br>)</pre><p><strong>iOS specific advantages:</strong></p><ul><li>Built in Cupertino widget library</li><li>Automatic iOS styling and animations</li><li>Consistent behavior across iOS versions</li><li>Good integration with iOS system features</li></ul><h3>Compose Multiplatform for iOS</h3><p>CMP brings Compose’s declarative approach to iOS development:</p><pre>// Compose Multiplatform on iOS<br>@Composable<br>fun iOSScreen(userRepository: UserRepository) {<br>    val users by userRepository.getUsers().collectAsState()<br>    <br>    Column {<br>        // iOS style navigation bar<br>        Box(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .background(Color.Gray.copy(alpha = 0.1f))<br>                .padding(16.dp)<br>        ) {<br>            Text(<br>                &quot;iOS App&quot;,<br>                style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.Bold),<br>                modifier = Modifier.align(Alignment.Center)<br>            )<br>        }<br>        <br>        // iOS style list<br>        LazyColumn(<br>            modifier = Modifier.fillMaxSize(),<br>            contentPadding = PaddingValues(16.dp),<br>            verticalArrangement = Arrangement.spacedBy(8.dp)<br>        ) {<br>            items(users) { user -&gt;<br>                Card(<br>                    modifier = Modifier.fillMaxWidth(),<br>                    shape = RoundedCornerShape(12.dp),<br>                    backgroundColor = Color.White<br>                ) {<br>                    Row(<br>                        modifier = Modifier<br>                            .fillMaxWidth()<br>                            .padding(16.dp),<br>                        verticalAlignment = Alignment.CenterVertically<br>                    ) {<br>                        Icon(<br>                            imageVector = Icons.Default.Person,<br>                            contentDescription = null,<br>                            tint = Color.Blue<br>                        )<br>                        Spacer(modifier = Modifier.width(12.dp))<br>                        Text(<br>                            text = user.name,<br>                            style = TextStyle(fontSize = 16.sp)<br>                        )<br>                        Spacer(modifier = Modifier.weight(1f))<br>                        Icon(<br>                            imageVector = Icons.Default.KeyboardArrowRight,<br>                            contentDescription = null,<br>                            tint = Color.Gray<br>                        )<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>iOS specific advantages:</strong></p><ul><li>Shared UI code between Android and iOS</li><li>Kotlin native performance on iOS</li><li>Access to iOS platform APIs through expect/actual declarations</li><li>Consistent development experience across platforms</li></ul><h3>Mobile UI Performance Comparison</h3><h3>Flutter on Mobile</h3><p>Flutter’s performance characteristics on Android and iOS:</p><p><strong>Android Performance:</strong></p><ul><li>Consistent 60fps animations across different Android versions</li><li>Direct compilation to ARM code</li><li>Predictable performance regardless of device manufacturer</li><li>Memory usage higher than native due to Flutter engine</li></ul><p><strong>iOS Performance:</strong></p><ul><li>Smooth animations matching iOS standards</li><li>Good performance on older iOS devices</li><li>App size tends to be larger than native iOS apps</li><li>Cold start time slightly slower than native</li></ul><h3>Compose Multiplatform Performance on Mobile</h3><p>Since CMP uses Compose for both platforms:</p><p><strong>Shared Performance Benefits:</strong></p><ul><li>Consistent declarative UI performance across Android and iOS</li><li>Kotlin/Native compilation for iOS provides near native performance</li><li>Shared UI logic reduces code duplication and potential bugs</li><li>Efficient rendering with Compose’s recomposition system</li></ul><p><strong>Platform Specific Optimizations:</strong></p><ul><li>Android: Full native Jetpack Compose performance</li><li>iOS: Kotlin/Native compilation optimized for iOS hardware</li></ul><h3>Design System Implementation</h3><h3>Flutter’s Approach</h3><p>Flutter excels at implementing consistent design systems across both platforms:</p><pre>// Custom theme implementation for both Android and iOS<br>ThemeData(<br>  primarySwatch: Colors.blue,<br>  textTheme: TextTheme(<br>    headline1: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),<br>    bodyText1: TextStyle(fontSize: 16),<br>  ),<br>  elevatedButtonTheme: ElevatedButtonThemeData(<br>    style: ElevatedButton.styleFrom(<br>      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),<br>    ),<br>  ),<br>)<br><br>// Platform specific adaptations<br>Widget buildButton() {<br>  return Platform.isIOS <br>    ? CupertinoButton.filled(child: Text(&#39;Submit&#39;), onPressed: () {})<br>    : ElevatedButton(child: Text(&#39;Submit&#39;), onPressed: () {});<br>}</pre><p><strong>Benefits:</strong></p><ul><li>Centralized theming system for both platforms</li><li>Easy to maintain design consistency</li><li>Custom component libraries work identically on Android and iOS</li><li>Built in Material Design and Cupertino components</li></ul><h3>Compose Multiplatform’s Approach</h3><p>CMP allows you to share UI components and design systems across both platforms:</p><pre>// Shared design system<br>object AppTheme {<br>    val primaryColor = Color(0xFF2196F3)<br>    val backgroundColor = Color(0xFFF5F5F5)<br>    val typography = Typography(<br>        h1 = TextStyle(fontSize = 32.sp, fontWeight = FontWeight.Bold),<br>        body1 = TextStyle(fontSize = 16.sp)<br>    )<br>}<br><br>// Shared UI components<br>@Composable<br>fun CustomButton(<br>    text: String,<br>    onClick: () -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) {<br>    Button(<br>        onClick = onClick,<br>        modifier = modifier,<br>        shape = RoundedCornerShape(8.dp),<br>        colors = ButtonDefaults.buttonColors(<br>            backgroundColor = AppTheme.primaryColor<br>        )<br>    ) {<br>        Text(<br>            text = text,<br>            style = AppTheme.typography.button<br>        )<br>    }<br>}<br>// Platform specific adaptations when needed<br>@Composable<br>expect fun PlatformSpecificComponent()<br>@Composable<br>actual fun PlatformSpecificComponent() {<br>    // Android implementation using Material components<br>}<br>@Composable<br>actual fun PlatformSpecificComponent() {<br>    // iOS implementation with iOS appropriate styling<br>}</pre><p><strong>Benefits:</strong></p><ul><li>Single Compose codebase for UI across platforms</li><li>Platform specific customizations when needed</li><li>Familiar development experience for Android developers</li><li>Shared design tokens and component libraries</li></ul><h3>Library Ecosystem &amp; Community</h3><h3>Flutter Ecosystem</h3><p>Flutter boasts one of the most comprehensive cross platform ecosystems:</p><p><strong>Package Statistics (pub.dev):</strong></p><ul><li><strong>30,000+ packages</strong> available on pub.dev</li><li><strong>Popular UI libraries</strong>: GetX, Provider, Riverpod, Bloc, Flutter Hooks</li><li><strong>Animation libraries</strong>: Lottie, Rive, Flutter Animate, Simple Animations</li><li><strong>State management</strong>: Provider, Riverpod, Bloc, GetX, MobX</li><li><strong>Navigation</strong>: Go Router, Auto Route, Get, Beamer</li><li><strong>Networking</strong>: Dio, HTTP, Chopper, Retrofit for Dart</li></ul><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  # State management<br>  provider: ^6.0.5<br>  # Networking<br>  dio: ^5.3.2<br>  # Animations<br>  lottie: ^2.7.0<br>  # UI components<br>  flutter_staggered_grid_view: ^0.6.2<br>  # Charts<br>  fl_chart: ^0.64.0<br>  # Image loading<br>  cached_network_image: ^3.3.0</pre><p><strong>Community Size:</strong></p><ul><li><strong>GitHub stars</strong>: 165k+ stars on Flutter repository</li><li><strong>Stack Overflow</strong>: 100k+ Flutter questions</li><li><strong>Reddit</strong>: 150k+ members in r/FlutterDev</li><li><strong>Discord</strong>: 50k+ active Flutter developers</li><li><strong>YouTube</strong>: Thousands of Flutter tutorials and content creators</li></ul><h3>Compose Multiplatform Ecosystem</h3><p>CMP has a smaller but rapidly growing ecosystem:</p><p><strong>Package Statistics:</strong></p><ul><li><strong>Shared libraries</strong>: Growing ecosystem of CMP compatible libraries</li><li><strong>Android ecosystem</strong>: Full access to existing Jetpack Compose libraries</li><li><strong>Kotlin Multiplatform</strong>: Can leverage existing KMP libraries for business logic</li><li><strong>Platform specific</strong>: Access to native iOS and Android libraries when needed</li></ul><pre>// CMP ecosystem example<br>dependencies {<br>    commonMain {<br>        // UI<br>        implementation(compose.runtime)<br>        implementation(compose.foundation)<br>        implementation(compose.material3)<br>        // Navigation<br>        implementation(&quot;cafe.adriel.voyager:voyager-navigator:1.0.0&quot;)<br>        // Image loading<br>        implementation(&quot;io.github.qdsfdhvh:image-loader:1.6.7&quot;)<br>        // Networking (KMP)<br>        implementation(&quot;io.ktor:ktor-client-core:2.3.5&quot;)<br>    }<br>    androidMain {<br>        // Android specific libraries<br>        implementation(&quot;androidx.compose.material:material-icons-extended&quot;)<br>        implementation(&quot;com.google.accompanist:accompanist-systemuicontroller&quot;)<br>    }<br>    iosMain {<br>        // iOS specific integrations<br>    }<br>}</pre><p><strong>Community Size:</strong></p><ul><li><strong>GitHub stars</strong>: 15k+ stars on Compose Multiplatform repository</li><li><strong>Kotlin community</strong>: Part of the larger Kotlin ecosystem (48k+ GitHub stars)</li><li><strong>Stack Overflow</strong>: Growing number of CMP specific questions</li><li><strong>Slack</strong>: Active Kotlin Slack community with CMP channels</li><li><strong>Conferences</strong>: Regular talks at KotlinConf and Android conferences</li></ul><h3>Library Availability Comparison</h3><p><strong>Flutter Advantages:</strong></p><ul><li><strong>Mature ecosystem</strong>: 6+ years of package development</li><li><strong>Cross platform first</strong>: Most packages work on both Android and iOS</li><li><strong>Rich UI libraries</strong>: Extensive collection of pre built UI components</li><li><strong>Third party integrations</strong>: Wide support for services like Firebase, Stripe, etc.</li><li><strong>Learning resources</strong>: Abundant tutorials, courses, and documentation</li></ul><p><strong>CMP Advantages:</strong></p><ul><li><strong>Native library access</strong>: Can use platform specific libraries when needed</li><li><strong>Kotlin ecosystem</strong>: Leverage existing Kotlin/JVM libraries</li><li><strong>Android compatibility</strong>: Full access to existing Jetpack Compose libraries</li><li><strong>Quality over quantity</strong>: Smaller but well maintained library ecosystem</li><li><strong>Official backing</strong>: Strong support from JetBrains and Google</li></ul><h3>Community Activity &amp; Support</h3><p><strong>Flutter Community:</strong></p><ul><li><strong>More active</strong>: Larger daily active community</li><li><strong>Beginner friendly</strong>: Extensive beginner resources and tutorials</li><li><strong>Global reach</strong>: Strong communities in multiple countries and languages</li><li><strong>Job market</strong>: More Flutter job opportunities currently available</li><li><strong>Corporate adoption</strong>: Used by companies like Google, Alibaba, BMW, eBay</li></ul><p><strong>CMP Community:</strong></p><ul><li><strong>Developer quality</strong>: Often experienced Kotlin/Android developers</li><li><strong>Enterprise focus</strong>: Strong adoption in enterprise applications</li><li><strong>Growing rapidly</strong>: Fast growing community since stable release</li><li><strong>JetBrains support</strong>: Excellent tooling and IDE support</li><li><strong>Corporate interest</strong>: Companies migrating from native Android are exploring CMP</li></ul><h3>Documentation &amp; Learning Resources</h3><p><strong>Flutter:</strong></p><ul><li><strong>Comprehensive docs</strong>: Extensive official documentation</li><li><strong>Video content</strong>: Flutter’s official YouTube channel with regular updates</li><li><strong>Books</strong>: Multiple published books on Flutter development</li><li><strong>Courses</strong>: Numerous paid and free courses available</li><li><strong>Code samples</strong>: Large collection of sample apps and demos</li></ul><p><strong>CMP:</strong></p><ul><li><strong>Growing docs</strong>: Improving documentation with each release</li><li><strong>Official samples</strong>: Well maintained sample projects from JetBrains</li><li><strong>Kotlin expertise</strong>: Can leverage existing Kotlin learning resources</li><li><strong>Conference talks</strong>: Regular updates at KotlinConf and developer conferences</li><li><strong>IDE integration</strong>: Excellent development experience in Android Studio</li></ul><h3>Verdict: Ecosystem Maturity</h3><p><strong>Current State (2025):</strong></p><ul><li><strong>Flutter</strong>: More mature ecosystem with broader library support and larger community</li><li><strong>CMP</strong>: Smaller but growing ecosystem with high quality libraries and strong backing</li></ul><p><strong>Future Outlook:</strong></p><ul><li><strong>Flutter</strong>: Continued growth and stability in the ecosystem</li><li><strong>CMP</strong>: Rapid growth expected as more developers adopt Kotlin Multiplatform</li></ul><h3>Animation Capabilities</h3><h3>Flutter Animations</h3><p>Flutter has a mature and comprehensive animation system built from the ground up:</p><pre>// Implicit Animations (Easy)<br>AnimatedContainer(<br>  duration: Duration(milliseconds: 300),<br>  curve: Curves.easeInOut,<br>  height: isExpanded ? 200 : 100,<br>  width: isExpanded ? 200 : 100,<br>  color: isExpanded ? Colors.blue : Colors.red,<br>  child: Center(child: Text(&#39;Animated!&#39;)),<br>)<br><br>// Explicit Animations (Advanced)<br>class CustomAnimationWidget extends StatefulWidget {<br>  @override<br>  _CustomAnimationWidgetState createState() =&gt; _CustomAnimationWidgetState();<br>}<br>class _CustomAnimationWidgetState extends State&lt;CustomAnimationWidget&gt;<br>    with TickerProviderStateMixin {<br>  late AnimationController _controller;<br>  late Animation&lt;double&gt; _scaleAnimation;<br>  late Animation&lt;double&gt; _rotationAnimation;<br>  @override<br>  void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      duration: Duration(seconds: 2),<br>      vsync: this,<br>    );<br>    <br>    _scaleAnimation = Tween&lt;double&gt;(begin: 1.0, end: 1.5).animate(<br>      CurvedAnimation(parent: _controller, curve: Curves.elasticOut)<br>    );<br>    <br>    _rotationAnimation = Tween&lt;double&gt;(begin: 0.0, end: 1.0).animate(<br>      CurvedAnimation(parent: _controller, curve: Curves.linear)<br>    );<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedBuilder(<br>      animation: _controller,<br>      builder: (context, child) {<br>        return Transform.scale(<br>          scale: _scaleAnimation.value,<br>          child: Transform.rotate(<br>            angle: _rotationAnimation.value * 2 * 3.14159,<br>            child: Container(<br>              width: 100,<br>              height: 100,<br>              color: Colors.blue,<br>            ),<br>          ),<br>        );<br>      },<br>    );<br>  }<br>}</pre><p><strong>Flutter Animation Strengths:</strong></p><ul><li><strong>Rich animation APIs</strong>: Implicit animations, explicit animations, custom animations</li><li><strong>60fps performance</strong>: Smooth animations across all devices</li><li><strong>Built in curves</strong>: Extensive easing curves library (Curves.easeIn, Curves.bounceOut, etc.)</li><li><strong>Hero animations</strong>: Seamless shared element transitions between screens</li><li><strong>Lottie support</strong>: Easy integration with After Effects animations via Lottie</li><li><strong>Custom painters</strong>: Create complex custom animations with CustomPainter</li></ul><h3>Compose Multiplatform Animations</h3><p>CMP brings Jetpack Compose’s animation system to both Android and iOS:</p><pre>// Simple Animations<br>@Composable<br>fun AnimatedButton() {<br>    var isExpanded by remember { mutableStateOf(false) }<br>    <br>    val size by animateDpAsState(<br>        targetValue = if (isExpanded) 200.dp else 100.dp,<br>        animationSpec = spring(<br>            dampingRatio = Spring.DampingRatioMediumBouncy,<br>            stiffness = Spring.StiffnessLow<br>        )<br>    )<br>    <br>    val color by animateColorAsState(<br>        targetValue = if (isExpanded) Color.Blue else Color.Red,<br>        animationSpec = tween(300)<br>    )<br>    <br>    Box(<br>        modifier = Modifier<br>            .size(size)<br>            .background(color, RoundedCornerShape(8.dp))<br>            .clickable { isExpanded = !isExpanded }<br>    )<br>}<br><br>// Complex Animations<br>@Composable<br>fun ComplexAnimation() {<br>    val infiniteTransition = rememberInfiniteTransition()<br>    <br>    val scale by infiniteTransition.animateFloat(<br>        initialValue = 1f,<br>        targetValue = 1.5f,<br>        animationSpec = infiniteRepeatable(<br>            animation = tween(1000, easing = FastOutSlowInEasing),<br>            repeatMode = RepeatMode.Reverse<br>        )<br>    )<br>    <br>    val rotation by infiniteTransition.animateFloat(<br>        initialValue = 0f,<br>        targetValue = 360f,<br>        animationSpec = infiniteRepeatable(<br>            animation = tween(2000, easing = LinearEasing),<br>            repeatMode = RepeatMode.Restart<br>        )<br>    )<br>    <br>    Box(<br>        modifier = Modifier<br>            .size(100.dp)<br>            .scale(scale)<br>            .rotate(rotation)<br>            .background(Color.Blue, CircleShape)<br>    )<br>}<br>// Shared Element Transitions (Preview feature)<br>@OptIn(ExperimentalSharedTransitionApi::class)<br>@Composable<br>fun SharedElementExample() {<br>    SharedTransitionLayout {<br>        // Shared element transitions between composables<br>        AnimatedContent(/* ... */) { targetState -&gt;<br>            // Content with shared elements<br>        }<br>    }<br>}</pre><p><strong>CMP Animation Strengths:</strong></p><ul><li><strong>Declarative approach</strong>: Animations feel natural within Compose’s paradigm</li><li><strong>Built in spring physics</strong>: Realistic spring based animations</li><li><strong>Coroutine integration</strong>: Smooth integration with Kotlin coroutines for complex sequences</li><li><strong>Shared element transitions</strong>: Built in support for hero like animations</li><li><strong>Performance</strong>: Native performance on both Android and iOS</li></ul><p><strong>Animation Comparison Summary:</strong></p><ul><li><strong>Flutter</strong>: More mature animation ecosystem, extensive documentation, richer built in animations</li><li><strong>CMP</strong>: Modern declarative approach, good performance, but newer ecosystem with fewer animation libraries</li></ul><h3>When to Choose Flutter</h3><p>Flutter works exceptionally well for:</p><ul><li><strong>Rapid prototyping</strong>: Quick MVP development for both Android and iOS</li><li><strong>Design heavy apps</strong>: Apps with custom, branded UIs that need consistency</li><li><strong>Cross platform consistency</strong>: When identical UX across platforms is crucial</li><li><strong>Rich animations</strong>: Apps requiring complex animations and visual effects</li><li><strong>Small to medium teams</strong>: When you want to maximize code sharing with limited resources</li><li><strong>Consumer apps</strong>: Social media, entertainment, e-commerce apps</li><li><strong>Mature ecosystem needs</strong>: When you need access to a wide variety of third party packages</li></ul><p><strong>Success Stories:</strong></p><ul><li>Google Ads app</li><li>Alibaba’s Xianyu app</li><li>BMW’s My BMW app</li><li>eBay Motors app</li><li>Tencent’s WeChat Work</li></ul><h3>When to Choose Compose Multiplatform</h3><p>CMP is ideal for:</p><ul><li><strong>Android first teams</strong>: Teams with strong Jetpack Compose experience expanding to iOS</li><li><strong>Gradual migration</strong>: Existing Android apps wanting to share UI logic with iOS</li><li><strong>Performance critical apps</strong>: When you need maximum performance on both platforms</li><li><strong>Platform specific features</strong>: Apps that need deep integration with platform capabilities</li><li><strong>Enterprise applications</strong>: When native platform integration is essential</li><li><strong>Kotlin centric development</strong>: Teams already invested in the Kotlin ecosystem</li></ul><p><strong>Success Stories:</strong></p><ul><li>JetBrains Toolbox app</li><li>Cash App (Block/Square) — using similar architecture</li><li>Netflix Android app — leveraging Compose</li><li>VMware workspace apps</li></ul><h3>The Verdict: Choose Based on Your Team and Requirements</h3><p>The choice between Flutter and Compose Multiplatform for mobile UI development depends on several factors:</p><p><strong>Choose Flutter if:</strong></p><ul><li>You want maximum code sharing including UI</li><li>Your team is new to mobile development</li><li>Design consistency across Android and iOS is paramount</li><li>You need rich animations and visual effects</li><li>You’re building consumer apps with custom designs</li><li>You want access to a mature package ecosystem</li><li>You want to get to market quickly with limited resources</li></ul><p><strong>Choose Compose Multiplatform if:</strong></p><ul><li>Your team has strong Android/Jetpack Compose expertise</li><li>You’re already building Android apps and want to expand to iOS</li><li>Native platform integration is crucial for your app</li><li>You prefer using the Kotlin ecosystem</li><li>You want to leverage existing Kotlin/Android team knowledge</li><li>Performance is a top priority</li></ul><h3>Looking Ahead: Future Considerations</h3><p><strong>Flutter’s Roadmap:</strong></p><ul><li>Continued expansion to web, desktop, and embedded platforms</li><li>Improving performance and reducing app size</li><li>Enhanced platform specific integrations</li><li>Growing ecosystem and community support</li></ul><p><strong>Compose Multiplatform’s Roadmap:</strong></p><ul><li>Stable web support and desktop improvements</li><li>Enhanced iOS integration and performance</li><li>Growing library ecosystem</li><li>Better tooling and development experience</li></ul><h3>Conclusion</h3><p>Both Flutter and Compose Multiplatform offer compelling approaches to mobile UI development. Flutter provides unmatched UI code sharing, a mature ecosystem, and excellent animation capabilities, while Compose Multiplatform offers the familiarity of Jetpack Compose extended to iOS with excellent performance characteristics and growing community support.</p><p><strong>Key Takeaways:</strong></p><ul><li><strong>Ecosystem</strong>: Flutter currently has a larger, more mature ecosystem</li><li><strong>Community</strong>: Flutter has a bigger community, but CMP is growing rapidly</li><li><strong>Animations</strong>: Flutter has more comprehensive animation libraries and documentation</li><li><strong>Performance</strong>: Both offer excellent performance, with CMP having slight edge due to native compilation</li><li><strong>Learning curve</strong>: Flutter is more beginner friendly, CMP leverages existing Kotlin knowledge</li></ul><p>The mobile development ecosystem benefits from having both approaches available. Your choice should align with your team’s expertise, project requirements, animation needs, and long term maintenance strategy. Consider the ecosystem maturity and community support as important factors in your decision making process.</p><p><em>Have you worked with Flutter or Compose Multiplatform for mobile UI development? Which ecosystem and community support has been more valuable for your projects? Share your experiences in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc6ac14a4090" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dark Side of Flutter Hot Reload: Why It’s Not Always Your Friend (and How to Tame It)]]></title>
            <link>https://medium.com/@naufalprakoso24/the-dark-side-of-flutter-hot-reload-why-its-not-always-your-friend-and-how-to-tame-it-9c3419d4cebd?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c3419d4cebd</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[hot-reload]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 10:40:39 GMT</pubDate>
            <atom:updated>2025-09-06T00:35:53.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*isuWN0TAwzX2utY7sMsr3w@2x.jpeg" /></figure><p><em>Discover the hidden pitfalls of Flutter’s most beloved feature and learn how to work around them like a pro</em></p><p>Flutter’s Hot Reload feature is often hailed as one of the framework’s greatest strengths. The ability to see code changes instantly reflected in your running app feels almost magical — until it doesn’t. While Hot Reload has revolutionized mobile development productivity, it comes with its own set of challenges that can frustrate even experienced developers.</p><p>Let’s dive deep into the dark side of Hot Reload and explore practical strategies to overcome its limitations.</p><h3>The Promise vs. Reality</h3><p>When Google introduced Hot Reload, it promised sub second refresh times and seamless development workflow. And for the most part, it delivers. But experienced Flutter developers know that Hot Reload isn’t infallible. Sometimes it fails silently, other times it gives misleading results, and occasionally it can even corrupt your app’s state.</p><h3>When Hot Reload Betrays You</h3><h3>1. State Preservation Gone Wrong</h3><p>One of Hot Reload’s core feature preserving app state can become its biggest weakness. When you’re debugging state related issues, Hot Reload might maintain corrupted or outdated state that doesn’t reflect your code changes.</p><p><strong>Example scenario:</strong></p><pre>class CounterWidget extends StatefulWidget {<br>  @override<br>  _CounterWidgetState createState() =&gt; _CounterWidgetState();<br>}<br><br>class _CounterWidgetState extends State&lt;CounterWidget&gt; {<br>  int _counter = 0; // This state persists through Hot Reload<br>  <br>  void _incrementCounter() {<br>    setState(() {<br>      _counter++; // Changes to this logic might not reflect properly<br>    });<br>  }<br>}</pre><p><strong>The problem:</strong> If you modify the increment logic while the counter is at 15, Hot Reload preserves that value, potentially masking bugs in your initialization code.</p><h3>2. Global Variables and Singletons</h3><p>Hot Reload doesn’t reset global variables or singleton instances, leading to inconsistent behavior between development and production.</p><pre>// This won&#39;t reset on Hot Reload<br>class ApiService {<br>  static final ApiService _instance = ApiService._internal();<br>  factory ApiService() =&gt; _instance;<br>  ApiService._internal();<br>  <br>  bool _isInitialized = false; // This state persists!<br>}</pre><h3>3. Asset and Resource Changes</h3><p>Modifying assets, fonts, or platform specific resources often requires a full restart, but Hot Reload might give you false confidence that changes have been applied.</p><h3>4. Constructor and initState() Modifications</h3><p>Changes to widget constructors or initState() methods frequently don&#39;t take effect with Hot Reload, as these are only called during widget creation.</p><pre>class MyWidget extends StatefulWidget {<br>  final String title;<br>  <br>  // Changes to default values won&#39;t Hot Reload<br>  MyWidget({this.title = &quot;Default Title&quot;});<br>  <br>  @override<br>  _MyWidgetState createState() =&gt; _MyWidgetState();<br>}<br><br>class _MyWidgetState extends State&lt;MyWidget&gt; {<br>  @override<br>  void initState() {<br>    super.initState();<br>    // Changes here often require Hot Restart<br>    setupInitialData();<br>  }<br>}</pre><h3>The Performance Trap</h3><p>While Hot Reload is fast, it’s not free. Each reload still triggers widget rebuilds and can impact performance during intensive development sessions. In complex apps with deep widget trees, frequent Hot Reloads can cause noticeable lag.</p><h3>Debugging Nightmares</h3><p>Hot Reload can create debugging scenarios where the running app doesn’t match your source code. This leads to:</p><ul><li><strong>Ghost bugs</strong>: Issues that appear to be fixed but resurface after restart</li><li><strong>Phantom features</strong>: Code that seems to work during development but fails in production</li><li><strong>State confusion</strong>: Debugging with stale state that doesn’t reflect current code</li></ul><h3>Taming the Hot Reload Beast</h3><h3>1. Know When to Hot Restart</h3><p>Learn to recognize scenarios that require Hot Restart (Ctrl+Shift+F5 or Cmd+Shift+F5):</p><ul><li>Constructor parameter changes</li><li>initState() modifications</li><li>Global variable updates</li><li>Enum value changes</li><li>Generic type parameter modifications</li></ul><h3>2. Implement Smart State Management</h3><p>Use state management solutions that work well with Hot Reload:</p><pre>// Use providers or riverpod for better Hot Reload compatibility<br>final counterProvider = StateProvider&lt;int&gt;((ref) =&gt; 0);<br><br>class CounterWidget extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final counter = ref.watch(counterProvider);<br>    <br>    return Column(<br>      children: [<br>        Text(&#39;Counter: $counter&#39;),<br>        ElevatedButton(<br>          onPressed: () =&gt; ref.read(counterProvider.notifier).state++,<br>          child: Text(&#39;Increment&#39;),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><h3>3. Create Hot Reload Friendly Code</h3><p>Structure your code to maximize Hot Reload effectiveness:</p><pre>// BAD: Complex logic in build method<br>class BadWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    // Complex calculations here won&#39;t Hot Reload well<br>    final processedData = complexDataProcessing();<br>    return Text(processedData);<br>  }<br>}<br><br>// GOOD: Extract logic to separate methods<br>class GoodWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Text(_getProcessedData());<br>  }<br>  <br>  String _getProcessedData() {<br>    // This will Hot Reload properly<br>    return complexDataProcessing();<br>  }<br>}</pre><h3>4. Use Development Flags</h3><p>Implement development only code that helps with Hot Reload debugging:</p><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;My App&#39;,<br>      // Add debug banner in development<br>      debugShowCheckedModeBanner: kDebugMode,<br>      home: kDebugMode ? DebugWrapper(child: HomeScreen()) : HomeScreen(),<br>    );<br>  }<br>}<br><br>class DebugWrapper extends StatelessWidget {<br>  final Widget child;<br>  <br>  DebugWrapper({required this.child});<br>  <br>  @override<br>  Widget build(BuildContext context) {<br>    // This wrapper can help identify Hot Reload issues<br>    return Banner(<br>      message: &#39;HOT RELOAD ACTIVE&#39;,<br>      location: BannerLocation.topEnd,<br>      child: child,<br>    );<br>  }<br>}</pre><h3>5. Embrace Hot Restart</h3><p>Don’t fight Hot Restart — embrace it as part of your workflow. Create keyboard shortcuts and make it a habit to restart when working on:</p><ul><li>State initialization</li><li>App startup logic</li><li>Platform specific code</li><li>Asset integration</li></ul><h3>6. Test Beyond Hot Reload</h3><p>Always test your changes with full app restarts and on physical devices. Create a testing checklist:</p><ul><li>✅ Works with Hot Reload</li><li>✅ Works with Hot Restart</li><li>✅ Works with fresh app launch</li><li>✅ Works on physical device</li><li>✅ Works in release mode</li></ul><h3>Advanced Hot Reload Strategies</h3><h3>Custom Hot Reload Handlers</h3><p>For complex scenarios, implement custom hot reload handling:</p><pre>class HotReloadAwareWidget extends StatefulWidget {<br>  @override<br>  _HotReloadAwareWidgetState createState() =&gt; _HotReloadAwareWidgetState();<br>}<br><br>class _HotReloadAwareWidgetState extends State&lt;HotReloadAwareWidget&gt; {<br>  @override<br>  void reassemble() {<br>    super.reassemble();<br>    // This method is called during Hot Reload<br>    // Use it to reset state when needed<br>    _resetToInitialState();<br>  }<br>  <br>  void _resetToInitialState() {<br>    // Custom logic to handle Hot Reload<br>  }<br>}</pre><h3>Environment Specific Behavior</h3><pre>class ConfigService {<br>  static bool get isHotReloadEnvironment {<br>    return kDebugMode &amp;&amp; Platform.environment.containsKey(&#39;FLUTTER_HOT_RELOAD&#39;);<br>  }<br>  <br>  static void handleHotReload() {<br>    if (isHotReloadEnvironment) {<br>      // Special handling for Hot Reload scenarios<br>      _clearCaches();<br>      _reinitializeServices();<br>    }<br>  }<br>}</pre><h3>Conclusion</h3><p>Hot Reload is undoubtedly one of Flutter’s killer features, but like any powerful tool, it requires understanding and respect. By recognizing its limitations and implementing the strategies outlined above, you can maintain the productivity benefits while avoiding the pitfalls.</p><p>Remember: Hot Reload is meant to accelerate development, not replace proper testing and validation. Use it wisely, complement it with Hot Restart when necessary, and always validate your changes in production like environments.</p><p>The key to mastering Flutter development isn’t just knowing how to use Hot Reload — it’s knowing when not to rely on it.</p><p><em>Have you encountered other Hot Reload gotchas? Share your experiences in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c3419d4cebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Unit Tests Repositories: From API Mocking to Error Handling]]></title>
            <link>https://medium.com/@naufalprakoso24/flutter-unit-tests-repositories-from-api-mocking-to-error-handling-6d8cf833aea0?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d8cf833aea0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 02:48:27 GMT</pubDate>
            <atom:updated>2025-09-06T00:37:34.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Testing Fundamentals: Beyond the Basic Tutorial</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*D6luZ8cUtxyl5WRZbYSTwA@2x.jpeg" /></figure><p>Testing is one of the most crucial skills every Flutter developer should master, yet it’s often overlooked or done poorly. In this article, we’ll dive deep into writing comprehensive unit tests for a Pokemon repository, covering everything from basic API mocking to advanced error handling scenarios.</p><p>By the end of this guide, you’ll understand how to:</p><ul><li>Set up proper test structure and organization</li><li>Mock HTTP clients effectively</li><li>Test both success and failure scenarios</li><li>Handle edge cases like malformed data</li><li>Write maintainable and readable tests</li></ul><h3>The Foundation: Understanding What We’re Testing</h3><p>Before jumping into the code, let’s understand our target: a PokemonRepositoryImpl class that fetches Pokemon data from the PokeAPI. This repository follows clean architecture principles, separating data concerns from business logic.</p><p>Our repository has one main method: fetchPokemonList() which:</p><ul><li>Makes HTTP requests to the Pokemon API</li><li>Handles pagination with limit and offset parameters</li><li>Transforms raw JSON into domain entities</li><li>Manages errors gracefully</li></ul><h3>Setting Up Your Test Environment</h3><p>First, ensure you have the necessary dependencies in your pubspec.yaml:</p><pre>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  http: ^1.1.0</pre><p>The http package includes testing utilities that make mocking HTTP requests straightforward.</p><h3>Test Structure: The AAA Pattern</h3><p>Every good unit test follows the <strong>Arrange Act Assert</strong> pattern:</p><ol><li><strong>Arrange</strong>: Set up test data and mocks</li><li><strong>Act</strong>: Execute the method being tested</li><li><strong>Assert</strong>: Verify the results</li></ol><p>Let’s see this in action with our first test:</p><pre>test(&#39;should return PokemonList when API call is successful&#39;, () async {<br>  // Arrange<br>  final mockResponse = {<br>    &#39;count&#39;: 100,<br>    &#39;next&#39;: &#39;https://pokeapi.co/api/v2/pokemon?offset=20&amp;limit=20&#39;,<br>    &#39;previous&#39;: null,<br>    &#39;results&#39;: [<br>      {<br>        &#39;name&#39;: &#39;bulbasaur&#39;,<br>        &#39;url&#39;: &#39;https://pokeapi.co/api/v2/pokemon/1/&#39;<br>      },<br>      {<br>        &#39;name&#39;: &#39;ivysaur&#39;,<br>        &#39;url&#39;: &#39;https://pokeapi.co/api/v2/pokemon/2/&#39;<br>      }<br>    ]<br>  };<br><br>  final mockClient = MockClient((request) async {<br>    if (request.url.toString() == &#39;https://pokeapi.co/api/v2/pokemon?limit=20&amp;offset=0&#39;) {<br>      return http.Response(json.encode(mockResponse), 200);<br>    }<br>    return http.Response(&#39;Not Found&#39;, 404);<br>  });<br><br>  final repository = PokemonRepositoryImpl(client: mockClient);<br><br>  // Act<br>  final result = await repository.fetchPokemonList();<br><br>  // Assert<br>  expect(result, isA&lt;PokemonList&gt;());<br>  expect(result.count, 100);<br>  expect(result.results.length, 2);<br>  expect(result.results[0].name, &#39;bulbasaur&#39;);<br>});</pre><h3>Deep Dive: HTTP Mocking with MockClient</h3><p>The MockClient is your best friend when testing HTTP dependent code. It allows you to simulate server responses without making actual network calls.</p><h3>Key Benefits of MockClient:</h3><ul><li><strong>Fast execution</strong>: No network delays</li><li><strong>Reliable</strong>: Tests don’t fail due to network issues</li><li><strong>Controllable</strong>: You define exactly what responses to return</li></ul><h3>Advanced MockClient Usage:</h3><pre>final mockClient = MockClient((request) async {<br>  // Check the exact URL being requested<br>  if (request.url.toString() == &#39;https://pokeapi.co/api/v2/pokemon?limit=5&amp;offset=10&#39;) {<br>    return http.Response(json.encode(customResponse), 200);<br>  }<br>  <br>  // Default fallback for unexpected requests<br>  return http.Response(&#39;Not Found&#39;, 404);<br>});</pre><p>This approach ensures your tests verify that the correct URLs are being constructed with proper query parameters.</p><h3>Testing Parameter Handling</h3><p>Real world APIs often require parameters. Here’s how to test that your repository correctly handles them:</p><pre>test(&#39;should use custom limit and offset parameters&#39;, () async {<br>  final mockResponse = {<br>    &#39;count&#39;: 50,<br>    &#39;next&#39;: &#39;https://pokeapi.co/api/v2/pokemon?offset=15&amp;limit=5&#39;,<br>    &#39;previous&#39;: &#39;https://pokeapi.co/api/v2/pokemon?offset=5&amp;limit=5&#39;,<br>    &#39;results&#39;: [<br>      {<br>        &#39;name&#39;: &#39;beedrill&#39;,<br>        &#39;url&#39;: &#39;https://pokeapi.co/api/v2/pokemon/15/&#39;<br>      }<br>    ]<br>  };<br><br>  final mockClient = MockClient((request) async {<br>    // Verify the URL contains the correct parameters<br>    if (request.url.toString() == &#39;https://pokeapi.co/api/v2/pokemon?limit=5&amp;offset=10&#39;) {<br>      return http.Response(json.encode(mockResponse), 200);<br>    }<br>    return http.Response(&#39;Not Found&#39;, 404);<br>  });<br><br>  final repository = PokemonRepositoryImpl(client: mockClient);<br>  <br>  // Test with specific parameters<br>  final result = await repository.fetchPokemonList(limit: 5, offset: 10);<br><br>  expect(result.count, 50);<br>  expect(result.results[0].name, &#39;beedrill&#39;);<br>});</pre><p>This test ensures that when you pass parameters to your method, they’re correctly included in the HTTP request.</p><h3>Error Handling: The Make or Break Factor</h3><p>Robust applications handle errors gracefully. Your tests should verify this behavior:</p><h3>Testing HTTP Error Codes:</h3><pre>test(&#39;should throw exception when API returns non 200 status code&#39;, () async {<br>  final mockClient = MockClient((request) async {<br>    return http.Response(&#39;Internal Server Error&#39;, 500);<br>  });<br><br>  final repository = PokemonRepositoryImpl(client: mockClient);<br><br>  expect(<br>    () =&gt; repository.fetchPokemonList(),<br>    throwsA(predicate((e) =&gt; <br>      e is Exception &amp;&amp; <br>      e.toString().contains(&#39;Failed to load Pokemon list: 500&#39;)<br>    )),<br>  );<br>});</pre><h3>Testing Network Errors:</h3><pre>test(&#39;should throw exception when network error occurs&#39;, () async {<br>  final mockClient = MockClient((request) async {<br>    throw Exception(&#39;Network error&#39;);<br>  });<br><br>  final repository = PokemonRepositoryImpl(client: mockClient);<br><br>  expect(<br>    () =&gt; repository.fetchPokemonList(),<br>    throwsA(predicate((e) =&gt; <br>      e is Exception &amp;&amp; <br>      e.toString().contains(&#39;Error fetching Pokemon list&#39;)<br>    )),<br>  );<br>});</pre><h3>Edge Cases: The Devil in the Details</h3><p>Professional developers anticipate edge cases. Here are some critical scenarios to test:</p><h3>Empty Results:</h3><pre>test(&#39;should handle empty results list&#39;, () async {<br>  final mockResponse = {<br>    &#39;count&#39;: 0,<br>    &#39;next&#39;: null,<br>    &#39;previous&#39;: null,<br>    &#39;results&#39;: []<br>  };<br><br>  final mockClient = MockClient((request) async {<br>    return http.Response(json.encode(mockResponse), 200);<br>  });<br><br>  final repository = PokemonRepositoryImpl(client: mockClient);<br>  final result = await repository.fetchPokemonList();<br><br>  expect(result.count, 0);<br>  expect(result.results, isEmpty);<br>});</pre><h3>Malformed JSON:</h3><pre>test(&#39;should handle malformed JSON response&#39;, () async {<br>  final mockClient = MockClient((request) async {<br>    return http.Response(&#39;invalid json&#39;, 200);<br>  });<br><br>  final repository = PokemonRepositoryImpl(client: mockClient);<br><br>  expect(<br>    () =&gt; repository.fetchPokemonList(),<br>    throwsA(predicate((e) =&gt; <br>      e is Exception &amp;&amp; <br>      e.toString().contains(&#39;Error fetching Pokemon list&#39;)<br>    )),<br>  );<br>});</pre><h3>Advanced Testing Techniques</h3><h3>Using Predicate Matchers</h3><p>The predicate matcher allows for complex assertions:</p><pre>throwsA(predicate((e) =&gt; <br>  e is Exception &amp;&amp; <br>  e.toString().contains(&#39;specific error message&#39;)<br>))</pre><p>This is more flexible than exact string matching and allows your error messages to evolve without breaking tests.</p><h3>Testing Data Transformation</h3><p>Notice how our test verifies that URLs are transformed into image URLs:</p><pre>expect(result.results[0].imageUrl, <br>  &#39;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png&#39;);</pre><p>This ensures your repository correctly transforms raw API data into the format your domain expects.</p><h3>Best Practices for Maintainable Tests</h3><h3>1. Use Descriptive Test Names</h3><p>Your test names should clearly describe what they’re testing:</p><ul><li>✅ &#39;should return PokemonList when API call is successful&#39;</li><li>❌ &#39;test fetchPokemonList&#39;</li></ul><h3>2. Group Related Tests</h3><p>Use group() to organize tests logically:</p><pre>group(&#39;PokemonRepositoryImpl&#39;, () {<br>  group(&#39;fetchPokemonList&#39;, () {<br>    // All fetchPokemonList tests here<br>  });<br>  <br>  group(&#39;fetchPokemonDetails&#39;, () {<br>    // Pokemon details tests here<br>  });<br>});</pre><h3>3. Keep Tests Independent</h3><p>Each test should be able to run in isolation. Avoid shared state between tests.</p><h3>4. Test One Thing at a Time</h3><p>Each test should verify one specific behavior. If you’re testing multiple things, consider splitting into separate tests.</p><h3>Common Pitfalls to Avoid</h3><h3>1. Over Mocking</h3><p>Don’t mock everything. Only mock external dependencies like HTTP clients, databases, or other services.</p><h3>2. Testing Implementation Details</h3><p>Test behavior, not implementation. If you refactor your code and tests break without changing behavior, you’re testing implementation details.</p><h3>3. Ignoring Async/Await</h3><p>Always properly handle asynchronous operations in tests:</p><pre>test(&#39;async test&#39;, () async {  // Mark test as async<br>  final result = await repository.fetchPokemonList();  // Await async calls<br>  expect(result, isNotNull);<br>});</pre><h3>4. Weak Assertions</h3><p>Be specific in your assertions:</p><ul><li>✅ expect(result.results.length, 2)</li><li>❌ expect(result.results, isNotEmpty)</li></ul><h3>Running and Organizing Your Tests</h3><h3>Running Tests</h3><pre># Run all tests<br>flutter test<br><br># Run specific test file<br>flutter test test/repositories/pokemon_repository_test.dart<br><br># Run with coverage<br>flutter test --coverage</pre><h3>Project Structure</h3><pre>test/<br>├── repositories/<br>│   ├── pokemon_repository_test.dart<br>│   └── user_repository_test.dart<br>├── services/<br>│   └── api_service_test.dart<br>└── helpers/<br>    └── test_helpers.dart</pre><h3>Conclusion</h3><p>Writing comprehensive unit tests might seem daunting at first, but it’s an investment that pays dividends. Good tests:</p><ul><li>Catch bugs before they reach production</li><li>Serve as documentation for your code</li><li>Enable confident refactoring</li><li>Improve code design through testability constraints</li></ul><p>The Pokemon repository example we’ve explored demonstrates all the essential testing patterns you’ll need:</p><ul><li>Successful API calls</li><li>Parameter handling</li><li>HTTP error scenarios</li><li>Network failures</li><li>Edge cases like empty data</li><li>Malformed responses</li></ul><p>Start with these patterns, and gradually expand your testing repertoire. Remember: the best test suite is one that gives you confidence to ship code without fear.</p><h3>What’s Next?</h3><p>Now that you’ve mastered repository testing, consider exploring:</p><ul><li>Widget testing for UI components</li><li>Integration testing for complete user flows</li><li>Test Driven Development (TDD) practices</li><li>Continuous integration with automated testing</li></ul><p>Happy testing! 🧪✨</p><p><em>Found this helpful? Follow me for more Flutter development tips and best practices.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d8cf833aea0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Debugging Flutter Apps in Android Studio]]></title>
            <link>https://medium.com/@naufalprakoso24/guide-to-debugging-flutter-apps-in-android-studio-db65f081bdad?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/db65f081bdad</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[android-studio]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 04:12:59 GMT</pubDate>
            <atom:updated>2025-09-06T00:39:44.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*umZd7k9SOawfA_-hHcS90A@2x.jpeg" /></figure><p><em>Master the art of Flutter debugging without cluttering your code with print statements</em></p><p>As Flutter developers, we’ve all been there staring at a screen with a bug that seems impossible to track down. While print() statements might seem like the quickest solution, there&#39;s a much more professional and efficient way to debug your Flutter applications using Android Studio&#39;s powerful debugging tools.</p><p>In this comprehensive guide, I’ll walk you through every debugging technique available in Android Studio, complete with step by step instructions and visual guides to help you become a debugging master.</p><h3>Why Debugging Tools Matter More Than Print Statements</h3><p>Before diving into the techniques, let’s understand why proper debugging tools are superior to print statements:</p><ul><li><strong>Interactive inspection</strong> of variables and objects</li><li><strong>Step by step execution</strong> control</li><li><strong>Visual widget tree exploration</strong></li><li><strong>Real time performance monitoring</strong></li><li><strong>Clean code</strong> without debug artifacts</li><li><strong>Professional development workflow</strong></li></ul><h3>Setting Up Your Debug Environment</h3><h3>Prerequisites</h3><ul><li>Android Studio with Flutter and Dart plugins installed</li><li>Flutter SDK properly configured</li><li>Android emulator or physical device</li><li>A Flutter project ready for debugging</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhtPtEFPLrXCtySRNROmGA.png" /></figure><h3>1. Setting Up Web Based Debugging Environment</h3><h3>Launch Flutter with Web DevTools</h3><p>Start your debugging session with web based tools for the best experience:</p><pre># Method 1: Run with automatic DevTools launch<br>flutter run --debug<br><br># Copy the DevTools URL from terminal output<br># Example: http://127.0.0.1:9100<br># Method 2: Manual DevTools activation<br>flutter pub global activate devtools<br>flutter pub global run devtools<br><br># Method 3: Launch with specific port<br>flutter run --debug --devtools-port=9200</pre><h3>Accessing Web DevTools Interface</h3><ol><li>Run your Flutter app in debug mode using the command above</li><li>Copy the DevTools URL from the terminal output</li><li>Open the URL in your preferred web browser (Chrome recommended)</li><li>You’ll see the main DevTools dashboard with multiple debugging tabs</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-MQBAcfzwilk24fA5vOZA.png" /></figure><h3>2. Mastering Breakpoints in Web DevTools</h3><h3>Setting Breakpoints via Web Interface</h3><p>Breakpoints are your first line of defense against bugs. The web DevTools provides superior breakpoint management:</p><p><strong>How to set breakpoints in web DevTools:</strong></p><ol><li>Open the <strong>Debugger</strong> tab in web DevTools</li><li>Navigate to your Dart file in the file explorer</li><li>Click on the line number where you want to pause execution</li><li>A blue circle will appear, indicating an active breakpoint</li><li>The breakpoint will be triggered when code execution reaches that line</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWCHelp7fkf90qOKjfRl4A.png" /></figure><h3>Advanced Web DevTools Breakpoint Features</h3><p><strong>Conditional Breakpoints in Web DevTools:</strong> Set breakpoints that only trigger under specific conditions:</p><ol><li>Right click on an existing breakpoint in the web DevTools</li><li>Select “Edit breakpoint” from the context menu</li><li>Add your condition (e.g., response.results.length == 50)</li><li>The breakpoint will only trigger when the condition evaluates to true</li><li>View condition status in the Breakpoints panel</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*VgndEm2C545yd_2QVYsQ_A.png" /></figure><p><strong>Exception Breakpoints:</strong> Automatically pause when exceptions are thrown:</p><ol><li>In the web DevTools Debugger tab, find the “Pause on exceptions” toggle</li><li>Choose “All exceptions” or “Uncaught exceptions”</li><li>Your app will automatically pause when exceptions occur</li><li>Inspect the call stack and variables at the point of failure</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*sjwi3NxF2hKQwNdvVIJf8w.png" /></figure><h3>3. Web DevTools Debug Execution Control</h3><h3>Understanding the Web DevTools Debugger</h3><p>The web based debugger provides superior control and visibility:</p><ol><li><strong>Debugger Tab</strong>: Primary interface for code level debugging</li><li><strong>Call Stack Panel</strong>: Shows the execution path leading to current breakpoint</li><li><strong>Variables Panel</strong>: Displays all variables in current scope with expandable objects</li><li><strong>Console Panel</strong>: Interactive Dart console for evaluating expressions</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*YZ-XaSVV8nqAxaAJiJ6BVQ.png" /></figure><h3>Debug Control Actions</h3><p>When execution pauses at a breakpoint, use these web DevTools controls:</p><ul><li><strong>Resume (▶️):</strong> Continue execution until the next breakpoint</li><li><strong>Step Over (⤵️):</strong> Execute the current line and move to the next</li><li><strong>Step Into (⤴️):</strong> Enter into method calls to debug deeper</li><li><strong>Step Out (⤴️):</strong> Exit the current method and return to caller</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*x_CC20xRxcp7a2JsucSxsg.png" /></figure><h3>4. Web DevTools Variables and Expression Evaluation</h3><h3>Enhanced Variable Inspection in Web DevTools</h3><p>The web DevTools provides superior variable inspection capabilities:</p><p><strong>Advanced Variable Features:</strong></p><ul><li><strong>Hierarchical object exploration</strong> with unlimited depth</li><li><strong>Real time value updates</strong> as you step through code</li><li><strong>Type information</strong> displayed alongside values</li><li><strong>Collection viewers</strong> for Lists, Maps, and Sets with item counts</li><li><strong>Custom object formatting</strong> for better readability</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*X4-1KuVuzqKj-fgLZyUzVw.png" /></figure><h3>Interactive Expression Evaluation</h3><p>Web DevTools offers a powerful console for testing expressions:</p><ol><li>Navigate to the <strong>Console</strong> tab in web DevTools</li><li>Enter any valid Dart expression while paused at a breakpoint</li><li>See immediate results with proper formatting</li><li>Access all variables in current scope</li><li>Call methods and test logic without modifying source code</li></ol><p><strong>Key features:</strong></p><ul><li><strong>Auto completion</strong> for available variables and methods</li><li><strong>Multi line expressions</strong> for complex testing</li><li><strong>History navigation</strong> to reuse previous expressions</li><li><strong>Error handling</strong> with detailed stack traces</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*qN9Hryh6yUATfc9b7II-4g.png" /></figure><h3>5. Flutter Inspector in Web: Visual Widget Debugging</h3><h3>Accessing Flutter Inspector in Web Browser</h3><p>The Flutter Inspector in web browser provides a more robust and feature rich debugging experience:</p><ol><li>Run your app in debug mode using flutter run --debug</li><li>In the terminal output, look for the Flutter DevTools URL (usually starts with <a href="http://127.0.0.1:9100)">http://127.0.0.1:9100)</a></li><li>Copy and open this URL in your web browser</li><li>Alternatively, run flutter pub global activate devtools then flutter pub global run devtools</li><li>Connect to your running app using the connection URL</li></ol><h3>Key Web Inspector Features</h3><p><strong>Enhanced Widget Tree Navigation:</strong></p><ul><li>Interactive widget tree with better performance than embedded version</li><li>Click on widgets in the inspector to highlight them in your app</li><li>Use the “Select Widget Mode” to click on app widgets and locate them in the tree</li><li>Detailed widget properties panel with real time updates</li><li>Widget summary with render object information</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMCPnkTNq-faN52heLV4Rw.png" /></figure><p><strong>Advanced Layout Inspector:</strong></p><ul><li>Visual representation of widget constraints and sizing</li><li>Flex layout debugging with detailed flex properties</li><li>Overflow detection and visualization</li><li>Render tree exploration for performance analysis</li><li>Widget rebuild tracking</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*y3bjwE_Y4x5Ddg7QbGpHyw.png" /></figure><p><strong>Performance Profiler:</strong></p><ul><li>Frame timeline with detailed performance metrics</li><li>CPU profiler for identifying performance bottlenecks</li><li>Memory tab for tracking memory usage and detecting leaks</li><li>Network tab for monitoring HTTP requests and responses</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osbn52Ad9njmja8zqJuJWg.png" /></figure><h3>6. Advanced Web DevTools Features</h3><h3>Web DevTools Call Stack Analysis</h3><p>The web based call stack provides enhanced navigation capabilities:</p><ul><li><strong>Interactive call stack</strong> with clickable frames</li><li><strong>Source code preview</strong> for each stack frame</li><li><strong>Variable scope</strong> changes as you navigate the stack</li><li><strong>Async call stack</strong> tracking for Future and Stream debugging</li><li><strong>Stack frame filtering</strong> to focus on your code vs framework code</li></ul><h3>Comprehensive Performance Monitoring</h3><p><strong>Enhanced Performance Tab:</strong> The web DevTools Performance tab offers professional grade profiling:</p><ul><li><strong>Timeline view</strong> with frame by frame analysis</li><li><strong>CPU profiler</strong> with flame charts and call trees</li><li><strong>Memory profiler</strong> with allocation tracking</li><li><strong>Network profiler</strong> for HTTP request monitoring</li><li><strong>Widget rebuild tracking</strong> to identify unnecessary rebuilds</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*7G0fPue_Ebrf-drqskZE5w.png" /></figure><h3>Network Request Debugging</h3><p><strong>Advanced Network Tab:</strong> Monitor and debug all network activities:</p><ul><li><strong>Request/Response inspection</strong> with full headers and body</li><li><strong>Timing analysis</strong> for each network call</li><li><strong>Error tracking</strong> for failed requests</li><li><strong>WebSocket monitoring</strong> for real time connections</li><li><strong>GraphQL query inspection</strong> for API debugging</li></ul><h3>7. Memory and App Size Analysis</h3><h3>Web DevTools Memory Profiling</h3><p><strong>Comprehensive Memory Analysis:</strong> The Memory tab in web DevTools provides detailed insights:</p><ul><li><strong>Heap snapshots</strong> for memory leak detection</li><li><strong>Allocation tracking</strong> to find memory hotspots</li><li><strong>Object inspection</strong> with reference paths</li><li><strong>Memory timeline</strong> showing usage patterns over time</li><li><strong>Garbage collection monitoring</strong> for performance optimization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiYrVU42FTwM3bMsSHEjNA.png" /></figure><h3>App Size Analysis</h3><p><strong>App Size Tool:</strong> Analyze your app’s size breakdown:</p><ul><li><strong>Size by library</strong> to identify large dependencies</li><li><strong>Asset size analysis</strong> for images and other resources</li><li><strong>Code size breakdown</strong> by packages and classes</li><li><strong>Comparison tools</strong> for before/after size analysis</li></ul><h3>8. Logging and Console Integration</h3><h3>Professional Logging in Web DevTools</h3><p><strong>Enhanced Logging Tab:</strong> The web DevTools provides superior logging capabilities:</p><ul><li><strong>Structured log viewing</strong> with expandable objects</li><li><strong>Log level filtering</strong> (Verbose, Debug, Info, Warning, Error)</li><li><strong>Search and filtering</strong> across all log messages</li><li><strong>Log export</strong> for sharing with team members</li><li><strong>Real time log streaming</strong> during app execution</li></ul><h3>Advanced Console Features</h3><p><strong>Interactive Dart Console:</strong> Beyond simple expression evaluation:</p><pre>// Multi line expressions<br>var complexCalculation = myList<br>    .where((item) =&gt; item.isActive)<br>    .map((item) =&gt; item.value)<br>    .reduce((a, b) =&gt; a + b);<br><br>// Object inspection<br>print(myObject.runtimeType);<br>print(myObject.toString());<br><br>// Method calls<br>myService.debugStatus();</pre><p><strong>Console capabilities:</strong></p><ul><li><strong>Auto completion</strong> for all available APIs</li><li><strong>Command history</strong> with up/down arrow navigation</li><li><strong>Object pretty printing</strong> for complex data structures</li><li><strong>Async/await support</strong> for testing async operations</li></ul><h3>9. Debugging Common Flutter Issues with Web DevTools</h3><h3>Layout Debugging</h3><p><strong>Debug Widget Borders:</strong> Temporarily add borders to see widget boundaries:</p><pre>Container(<br>  decoration: BoxDecoration(<br>    border: Border.all(color: Colors.red, width: 2),<br>  ),<br>  child: YourWidget(),<br>)</pre><p><strong>Debug Size Constraints:</strong> Use debugPaintSizeEnabled = true to visualize widget sizes:</p><pre>import &#39;package:flutter/rendering.dart&#39;;<br><br>void main() {<br>  debugPaintSizeEnabled = true; // Enable size debugging<br>  runApp(MyApp());<br>}</pre><h3>State Management Debugging</h3><p><strong>Debug State Changes:</strong> Monitor state updates in StatefulWidgets:</p><pre>@override<br>void setState(VoidCallback fn) {<br>  developer.log(&#39;State change triggered&#39;, name: &#39;StateDebug&#39;);<br>  super.setState(fn);<br>}</pre><h3>Async Code Debugging</h3><p><strong>Debug Futures and Streams:</strong> Use breakpoints in async functions and track execution flow:</p><pre>Future&lt;void&gt; debugAsyncFunction() async {<br>  try {<br>    final result = await apiCall(); // Set breakpoint here<br>    // Process result<br>  } catch (e) {<br>    // Set breakpoint here for error handling<br>    developer.log(&#39;Async error: $e&#39;, name: &#39;AsyncDebug&#39;);<br>  }<br>}</pre><h3>10. Pro Tips for Web DevTools Efficiency</h3><h3>Web DevTools Workflow Best Practices</h3><ol><li><strong>Start with the Performance tab</strong> — Profile before debugging</li><li><strong>Use the Inspector tab</strong> — Visual debugging first, then code level</li><li><strong>Leverage breakpoints strategically</strong> — Use conditional breakpoints for efficiency</li><li><strong>Monitor the Console continuously</strong> — Keep it open for real time feedback</li><li><strong>Use multiple browser tabs</strong> — Different DevTools features in separate tabs</li></ol><h3>Web DevTools Keyboard Shortcuts</h3><p>Master these shortcuts for faster web based debugging:</p><ul><li>Ctrl + Shift + P - Command palette in DevTools</li><li>Ctrl + F - Search within current tab</li><li>F8 - Resume execution (when paused)</li><li>F10 - Step over in debugger</li><li>F11 - Step into in debugger</li><li>Shift + F11 - Step out in debugger</li><li>`Ctrl + `` — Toggle console panel</li></ul><h3>Browser Developer Tools Integration</h3><p><strong>Enhanced debugging with browser DevTools:</strong></p><ul><li>Use browser’s Network tab alongside Flutter Network tab</li><li>Leverage browser’s Performance profiler for web specific issues</li><li>Use browser’s Memory tab for additional memory insights</li><li>Access browser’s Console for JavaScript interop debugging</li></ul><h3>11. Advanced Web DevTools Configuration</h3><h3>Custom DevTools Configuration</h3><p><strong>DevTools Settings and Customization:</strong></p><ul><li><strong>Theme customization</strong> — Dark/light mode preferences</li><li><strong>Panel layout</strong> — Customize which panels are visible</li><li><strong>Default tab settings</strong> — Set preferred starting tab</li><li><strong>Performance settings</strong> — Adjust profiling sensitivity</li><li><strong>Memory settings</strong> — Configure heap snapshot frequency</li></ul><h3>Multiple Environment Debugging</h3><p><strong>Managing Different Flutter Targets:</strong></p><pre># Debug on different platforms simultaneously<br>flutter run --debug -d chrome           # Web version<br>flutter run --debug -d android          # Android version  <br>flutter run --debug -d ios              # iOS version<br><br># Each creates separate DevTools instances<br># Compare behavior across platforms</pre><h3>Team Collaboration with Web DevTools</h3><p><strong>Sharing Debug Sessions:</strong></p><ul><li><strong>Export performance profiles</strong> for team review</li><li><strong>Share DevTools URLs</strong> with specific debug states</li><li><strong>Screenshot/video recording</strong> of debugging sessions</li><li><strong>Export memory snapshots</strong> for offline analysis</li></ul><h3>12. Troubleshooting Web DevTools Issues</h3><h3>10. Troubleshooting Web DevTools Issues</h3><h3>Common Connection Problems</h3><p><strong>DevTools Won’t Connect:</strong></p><ol><li>Ensure Flutter app is running in debug mode</li><li>Check that DevTools URL matches the app’s debug service</li><li>Verify no firewall blocking the connection</li><li>Try refreshing the browser page</li><li>Restart both app and DevTools if connection persists</li></ol><p><strong>Port Conflicts:</strong></p><pre># Use specific ports to avoid conflicts<br>flutter run --debug --devtools-port=9201<br>flutter run --debug --observatory-port=8889</pre><h3>Performance Issues in Web DevTools</h3><p><strong>Optimization strategies:</strong></p><ul><li>Close unused DevTools tabs to reduce memory usage</li><li>Limit the number of active breakpoints</li><li>Use conditional breakpoints to reduce pause frequency</li><li>Clear console logs periodically</li><li>Restart DevTools session if it becomes sluggish</li></ul><h3>Browser Compatibility</h3><p><strong>Recommended browsers:</strong></p><ul><li><strong>Chrome/Chromium</strong> — Best performance and feature support</li><li><strong>Edge</strong> — Good alternative with similar performance</li><li><strong>Firefox</strong> — Basic functionality, some features may be limited</li><li><strong>Safari</strong> — Limited support, not recommended for debugging</li></ul><h3>Conclusion</h3><p>Mastering Flutter debugging in Android Studio transforms you from a developer who relies on print statements to a professional who can efficiently track down and fix bugs. The visual debugging tools, interactive inspection capabilities, and performance monitoring features make Android Studio an indispensable tool for Flutter development.</p><p>Remember, good debugging is not just about finding bugs — it’s about understanding your code’s behavior, optimizing performance, and building more robust applications.</p><p><strong>Key takeaways:</strong></p><ul><li>Use breakpoints instead of print statements</li><li>Leverage Flutter Inspector for widget debugging</li><li>Monitor performance proactively</li><li>Master keyboard shortcuts for efficiency</li><li>Understand the complete debugging workflow</li></ul><p>Start implementing these techniques in your next Flutter project, and you’ll notice a significant improvement in your debugging efficiency and code quality.</p><p><em>What debugging techniques do you find most helpful? Share your experience in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db65f081bdad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Linking Implementation for Flutter Apps]]></title>
            <link>https://medium.com/@naufalprakoso24/deep-linking-implementation-for-flutter-apps-5124a9957f19?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5124a9957f19</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[deep-linking]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Fri, 23 May 2025 07:29:08 GMT</pubDate>
            <atom:updated>2025-09-06T00:40:46.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*rk-ZmVSytZWCofNkyoh22w@2x.jpeg" /></figure><p>Deep linking is a critical component of modern mobile applications, allowing users to navigate directly to specific content within your app through URLs. For Flutter developers, implementing a reliable deep linking system presents unique challenges due to differences in platform behaviors and app states.</p><p>In this article, I’ll share how we implemented a robust deep linking system in Flutter application that effectively handles links across different app states (terminated, background, and foreground) while providing a seamless user experience.</p><h3>Understanding Deep Linking Challenges</h3><p>Before diving into implementation details, let’s understand why deep linking can be challenging:</p><ol><li><strong>Platform Differences</strong>: iOS and Android handle deep links differently, requiring separate configurations</li><li><strong>App State Variations</strong>: Deep links behave differently based on whether your app is terminated, in the background, or already running</li><li><strong>Link Validation</strong>: Not all incoming links are valid or should trigger navigation</li><li><strong>Duplicate Handling</strong>: Without proper safeguards, the same deep link might be processed multiple times</li><li><strong>Navigation Context</strong>: The app needs to navigate to the correct screen without disrupting the user experience</li></ol><p>This solution addresses all these challenges using a combination of the <a href="https://pub.dev/packages/app_links">app_links</a> package and native method channels, providing a bulletproof deep linking system.</p><h3>Core Implementation Architecture</h3><p>Let’s explore how to create a comprehensive deep linking manager for your Flutter app:</p><pre>import &#39;package:app_links/app_links.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:get/get.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;dart:async&#39;;<br><br>class DeepLinkManagement {<br>  final AppLinks _appLinks = AppLinks();<br><br>  static const MethodChannel _methodChannel = MethodChannel(&#39;app/deeplink&#39;);<br>  final StreamController&lt;Uri&gt; _deepLinkStreamController = StreamController&lt;Uri&gt;.broadcast();<br><br>  DateTime? _lastHandledAt;<br>  bool _handlingDeepLink = false;<br>  bool _isInitialized = false;<br>  bool _isProcessingDeepLink = false;<br>  Uri? _lastUri;<br><br>  // Implementation methods will go here<br>}</pre><h3>Initializing Deep Link Handling</h3><p>The initialization process is crucial for capturing deep links in all app states:</p><pre>Future&lt;void&gt; initDeepLink() async {<br>  if (_isInitialized) return;<br><br>  _isInitialized = true;<br><br>  try {<br>    // Set up method channel handler for native deep link events<br>    _methodChannel.setMethodCallHandler((call) async {<br>      if (call.method == &#39;deepLinkReceived&#39;) {<br>        final String? urlString = call.arguments as String?;<br>        if (urlString != null &amp;&amp; urlString.isNotEmpty) {<br>          try {<br>            final Uri uri = Uri.parse(urlString);<br>            _deepLinkStreamController.add(uri);<br><br>            if (!_isProcessingDeepLink) {<br>              _isProcessingDeepLink = true;<br>              WidgetsBinding.instance.addPostFrameCallback((_) {<br>                _handleDeepLinkNavigation(uri);<br>              });<br>            }<br>          } catch (e) {<br>            debugPrint(&quot;Error processing deeplink: $e&quot;);<br>          }<br>        }<br>      }<br>      return null;<br>    });<br><br>    // Check for initial deep link (app launched from terminated state)<br>    Future.delayed(const Duration(milliseconds: 500), () async {<br>      try {<br>        // Try getting initial link from native code<br>        final String? initialLink = await _methodChannel.invokeMethod&lt;String?&gt;(&#39;getInitialDeepLink&#39;);<br>        if (initialLink != null &amp;&amp; initialLink.isNotEmpty) {<br>          // Process native initial link<br>          // ...<br>        } else {<br>          // Fallback to app_links package for initial link<br>          try {<br>            final initialUri = await _appLinks.getInitialLink();<br>            if (initialUri != null) {<br>              // Process app_links initial link<br>              // ...<br>            }<br>          } catch (e) {<br>            debugPrint(&quot;Error getting initial link from app_links: $e&quot;);<br>          }<br>        }<br>      } catch (e) {<br>        debugPrint(&quot;Error getting initial link from native: $e&quot;);<br>      }<br>    });<br><br>    // Listen for links while app is running<br>    _appLinks.uriLinkStream.listen((uri) {<br>      debugPrint(&quot;App received new link while running: $uri&quot;);<br>      if (!_isProcessingDeepLink) {<br>        _isProcessingDeepLink = true;<br>        _handleDeepLinkNavigation(uri);<br>      }<br>    },<br>    onError: (error) {<br>      debugPrint(&quot;Error in uri link stream: $error&quot;);<br>    });<br><br>  } catch (e) {<br>    debugPrint(&quot;Error initializing deep links: $e&quot;);<br>    _isInitialized = false;<br>  }<br>}</pre><h3>Handling and Processing Deep Links</h3><p>Once a deep link is captured, we need a reliable mechanism to process it:</p><pre>void _handleDeepLinkNavigation(Uri? uri) async {<br>  if (uri == null || _handlingDeepLink) return;<br><br>  // Throttle handling to prevent rapid firing<br>  final now = DateTime.now();<br>  if (_lastHandledAt != null &amp;&amp;<br>      now.difference(_lastHandledAt!).inMilliseconds &lt; 1500) {<br>    debugPrint(&quot;Deeplink skipped - handled too recently&quot;);<br>    return;<br>  }<br><br>  // Prevent duplicate processing<br>  if (_lastUri?.toString() == uri.toString()) return;<br><br>  _handlingDeepLink = true;<br>  _lastUri = uri;<br>  _lastHandledAt = DateTime.now();<br><br>  try {<br>    // Check app state/context before proceeding<br>    final userIsLoggedIn = await checkUserLoggedIn();<br>    if (userIsLoggedIn) {<br>      debugPrint(&quot;User already logged in, ignoring deeplink&quot;);<br>      _cleanupDeepLinkState();<br>      return;<br>    }<br><br>    // Extract and validate parameters<br>    final email = uri.queryParameters[&#39;email&#39;];<br>    if (email == null || email.isEmpty) {<br>      debugPrint(&quot;Deeplink email is empty&quot;);<br>      _cleanupDeepLinkState();<br>      return;<br>    }<br><br>    final token = uri.pathSegments.length &gt;= 2 ? uri.pathSegments[1] : null;<br>    if (token == null || token.isEmpty) {<br>      debugPrint(&quot;Deeplink token is empty&quot;);<br>      _cleanupDeepLinkState();<br>      return;<br>    }<br><br>    // Navigate to appropriate screen<br>    WidgetsBinding.instance.addPostFrameCallback((_) {<br>      _navigateToTargetScreen(email, token);<br>    });<br><br>  } catch (e) {<br>    debugPrint(&quot;Error handling deeplink: $e&quot;);<br>    _cleanupDeepLinkState();<br>  }<br>}<br><br>void _cleanupDeepLinkState() {<br>  _handlingDeepLink = false;<br>  _isProcessingDeepLink = false;<br>}<br><br>void _navigateToTargetScreen(String email, String token) {<br>  debugPrint(&quot;Navigating to activation screen with $email and token $token&quot;);<br><br>  WidgetsBinding.instance.addPostFrameCallback((_) {<br>    // Use your navigation system (GetX in this example)<br>    Get.offAllNamed(<br>        &#39;activation_route&#39;,<br>        arguments: {<br>          &#39;email&#39;: email,<br>          &#39;isFromDeeplink&#39;: true,<br>          &#39;token&#39;: token,<br>        }<br>    );<br>    _isProcessingDeepLink = false;<br>  });<br>}</pre><h3>Platform Specific Configuration</h3><p>To make deep linking work, you need to configure both Android and iOS:</p><p><strong>Android Configuration (AndroidManifest.xml)</strong></p><pre>&lt;intent-filter android:autoVerify=&quot;true&quot;&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br><br>    &lt;!-- Web URL pattern --&gt;<br>    &lt;data android:scheme=&quot;https&quot; <br>          android:host=&quot;yourdomain.com&quot; <br>          android:pathPrefix=&quot;/verify-email&quot; /&gt;<br><br>    &lt;!-- Custom scheme --&gt;<br>    &lt;data android:scheme=&quot;yourappscheme&quot; <br>          android:host=&quot;verify-email&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p><strong>iOS Configuration (Info.plist)</strong></p><pre>&lt;key&gt;FlutterDeepLinkingEnabled&lt;/key&gt;<br>&lt;false/&gt;<br>&lt;key&gt;com.apple.developer.associated-domains&lt;/key&gt;<br>&lt;array&gt;<br>  &lt;string&gt;applinks:www.yourdomain.com&lt;/string&gt;<br>&lt;/array&gt;</pre><h3>Best Practices for Reliable Deep Linking</h3><p>Based on our implementation experience, here are key recommendations:</p><ol><li><strong>Multiple Capture Mechanisms</strong>: Use both app_links and native method channels for maximum reliability</li><li><strong>Throttling and Deduplication</strong>: Implement safeguards to prevent duplicate link handling</li><li><strong>Error Handling</strong>: Wrap deep link processing in try catch blocks and log errors for debugging</li><li><strong>State Management</strong>: Use flags to track processing state and prevent concurrent handling</li><li><strong>Context Awareness</strong>: Check app state before processing links (e.g., user already logged in)</li><li><strong>Post Frame Callbacks</strong>: Use WidgetsBinding.instance.addPostFrameCallback to ensure UI is ready before navigation</li></ol><h3>Common Pitfalls to Avoid</h3><ol><li><strong>Ignoring App State</strong>: Different handling is needed for terminated, background, and foreground states</li><li><strong>Overlooking Platform Differences</strong>: iOS and Android require different configurations</li><li><strong>Missing Error Handling</strong>: Deep link parsing can fail in unexpected ways</li><li><strong>Navigation Timing Issues</strong>: Navigating before the app is fully initialized can cause crashes</li><li><strong>Overriding Flutter’s Default Handler</strong>: If using packages like app_links, disable Flutter’s built in handler</li></ol><h3>Testing Your Deep Linking Implementation</h3><p>To thoroughly test your deep linking setup:</p><p><strong>Android Testing</strong></p><pre>adb shell am start -a android.intent.action.VIEW \<br> -c android.intent.category.BROWSABLE \<br> -d &quot;https://yourdomain.com/verify-email?email=test@example.com&quot;</pre><p><strong>iOS Testing</strong></p><pre>/usr/bin/xcrun simctl openurl booted &quot;https://yourdomain.com/verify-email?email=test@example.com&quot;</pre><h3>Conclusion</h3><p>Implementing robust deep linking in Flutter requires careful consideration of platform differences, app states, and potential edge cases. By combining the app_links package with native method channels and implementing proper safeguards, you can create a reliable deep<br> linking system that enhances your app’s user experience.</p><p>The approach outlined in this article has been battle tested in our production app, successfully handling of deep link activations across different devices and app states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-611fQkbCxNix-GG" /><figcaption>Photo by <a href="https://unsplash.com/@thematthoward?utm_source=medium&amp;utm_medium=referral">Matt Howard</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What deep linking challenges have you faced in your Flutter projects? Share your experiences in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5124a9957f19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Click Events on Notifications in Flutter]]></title>
            <link>https://medium.com/@naufalprakoso24/handling-click-events-on-notifications-in-flutter-f492fcaec5ca?source=rss-3294105e8e7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f492fcaec5ca</guid>
            <category><![CDATA[getx]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Naufal Prakoso]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 04:33:15 GMT</pubDate>
            <atom:updated>2025-08-10T07:58:54.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Iqx7rs_vutxauWYnjA55Cg@2x.jpeg" /></figure><p>Push notifications are an essential feature for engaging users in a Flutter application. However, handling notification clicks properly is crucial to ensure a smooth user experience. In this article, we’ll explore how to listen for and handle notification click events in Flutter using <strong>firebase_messaging</strong> and <strong>flutter_local_notifications</strong>.</p><h3>1. Setting Up Dependencies</h3><p>To manage push notifications, add the following dependencies in your pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  firebase_core: latest_version<br>  firebase_messaging: latest_version<br>  flutter_local_notifications: latest_version</pre><p>Then, run:</p><pre>flutter pub get</pre><h3>2. Configuring Firebase Messaging</h3><p>Initialize Firebase in your main.dart:</p><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp();<br>  <br>  runApp(MyApp());<br>}</pre><h3>Request Notification Permissions</h3><p>On iOS, request permission for push notifications:</p><pre>void requestPermission() async {<br>  FirebaseMessaging messaging = FirebaseMessaging.instance;<br>  NotificationSettings settings = await messaging.requestPermission(<br>    alert: true,<br>    badge: true,<br>    sound: true,<br>  );<br>}</pre><h3>3. Handling Click Events on Notifications</h3><h3>3.1 Foreground Click Handling</h3><p>When the app is in the foreground, Firebase Messaging’s onMessageOpenedApp is triggered when a user taps on a notification:</p><pre>FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {<br>  if (message.data[&#39;route&#39;] != null) {<br>    Get.toNamed(message.data[&#39;route&#39;]);<br>  }<br>});</pre><h3>3.2 Background and Terminated Click Handling</h3><p>For background or terminated states, use getInitialMessage:</p><pre>Future&lt;void&gt; handleInitialMessage() async {<br>  RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();<br>  if (initialMessage != null &amp;&amp; initialMessage.data[&#39;route&#39;] != null) {<br>    Get.toNamed(initialMessage.data[&#39;route&#39;]);<br>  }<br>}</pre><p>Call this function in main.dart after Firebase initialization.</p><h3>3.3 Local Notifications Click Handling</h3><p>If using flutter_local_notifications, configure click handling:</p><pre>void initializeLocalNotifications() {<br>  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();<br><br>  const AndroidInitializationSettings androidSettings =<br>      AndroidInitializationSettings(&#39;@mipmap/ic_launcher&#39;);<br>  final InitializationSettings initSettings =<br>      InitializationSettings(android: androidSettings);<br><br>  flutterLocalNotificationsPlugin.initialize(initSettings,<br>      onSelectNotification: (String? payload) async {<br>    if (payload != null) {<br>      Get.toNamed(payload);<br>    }<br>  });<br>}</pre><h3>4. Testing Notification Clicks</h3><h3>4.1 Sending Firebase Test Messages</h3><p>Use Firebase Cloud Messaging (FCM) to send a test push notification:</p><pre>{<br>  &quot;to&quot;: &quot;/topics/all&quot;,<br>  &quot;notification&quot;: {<br>    &quot;title&quot;: &quot;Hello!&quot;,<br>    &quot;body&quot;: &quot;Tap to open the app&quot;<br>  },<br>  &quot;data&quot;: {<br>    &quot;route&quot;: &quot;/home&quot;<br>  }<br>}</pre><h3>4.2 Debugging Click Events</h3><p>Add print logs inside listeners to track behavior:</p><pre>FirebaseMessaging.onMessageOpenedApp.listen((message) {<br>  print(&quot;Notification clicked: ${message.data}&quot;);<br>});</pre><h3>Conclusion</h3><p>Handling notification click events properly enhances user experience and engagement. By combining <strong>firebase_messaging</strong>and <strong>flutter_local_notifications</strong>, we can ensure smooth navigation when users interact with notifications.</p><p>Have you implemented notification click handling in your Flutter app? Share your thoughts in the comments! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f492fcaec5ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>