Search code examples
android-jetpack-composekotlin-multiplatformcompose-multiplatform

Image Loading from URL in Compose Multiplatform


I'm currently working on a project using Compose Multiplatform project, and looking for ways to handle image loading from a URL. However, since Coil isn't supported, I haven't found a solution.

I've come across a manual Ktor implementation that converts bitmaps, but it lacks caching support and other implementation details(e.g. loading, error states).

Has anyone integrated image loading using a library or found other alternatives for Compose Multiplatform?


Solution

  • Coil 3.0.0-alpha06 has multiplatform support, Ktor 3.0.0-wasm2 has javscript support

    Basic configuration below, typically shared/build.gradle.kts:

        kotlin {
            // targets configuration
            
            sourceSets {
                commonMain.dependencies {
                    implementation("io.coil-kt.coil3:coil-compose:3.0.0-alpha06")
                    implementation("io.coil-kt.coil3:coil-network-ktor:3.0.0-alpha06")
                }
                androidMain.dependencies {
                    implementation("io.ktor:ktor-client-okhttp:3.0.0-alpha06")
                }
                iosMain.dependencies {
                    implementation("io.ktor:ktor-client-darwin:3.0.0-alpha06")
                }
                jsMain.dependencies {
                    implementation("io.ktor:ktor-client-js:3.0.0-wasm2")
                }
            }
        }   
    

    IMPORTANT: To load images from a network URL in Coil 3.0 you'll need to import a separate artifact for each source set.

    Basic usage of AsyncImage:

    AsyncImage(
        model = "https://example.com/image.jpg", // replace with working URL 
        contentDescription = null
    )
    

    For more advanced usage over loading and error use SubcomposeAsyncImage

    If you already using coil 2.x, then check guide how to upgrade to coil 3.x