'How to set an image URL as error placeholder on Coil in Jetpack Compose

Coil accepts a drawable resource as an error placeholder. Is there a way to use an image URL here instead?

Here is the code I am working on:

// Global variables
var currentlySelectedImageUri = mutableStateOf<Uri?>(null)
var previousImageUri: Uri? = null

// @Composable fun() {...
Image(
    painter = rememberImagePainter(
    if (currentlySelectedImageUri.value != null) { // use the currently selected image
        currentlySelectedImageUri.value
    } else {
        if (previousImageUri != null) { // use the previously selected image
            previousImageUri
        } else {
            R.drawable.blank_profile_picture // use the placeholder image
        }
    }, builder = {
        placeholder(R.drawable.blank_profile_picture)
        error(R.drawable.blank_profile_picture) // FIXME: Set the previously selected image
    }),
    contentDescription = "profile image",
    contentScale = ContentScale.Crop,
    modifier = Modifier.fillMaxWidth()
)


Solution 1:[1]

Actually there is an easier way from coil compose api , you can just add error(R.drawable.your_placeholder_drawable) to the builder and that's it

Image(painter = rememberImagePainter(data = url, builder = {error(R.drawable.your_placeholder_drawable)}))

Solution 2:[2]

There is a function inside coil ImageRequest Builder class

  fun placeholder(@DrawableRes drawableResId: Int) = apply {
      this.placeholderResId = drawableResId
      this.placeholderDrawable = null
  }

Usage:

Image(
        painter = rememberImagePainter(
            data = url,
            builder = {
                placeholder(R.drawable.your_placeholder_drawable) // or bitmap
            }
        )
    )

UPDATE:

Also use: com.google.accompanist.placeholder

Dependency gradle: com.google.accompanist:accompanist-placeholder:accompanist_version

// accompanist_version = 0.19.0

Modifier.placeholder(
        visible =  true/false,
        color = color,
        highlight = PlaceholderHighlight.shimmer(color),
        shape = imageShape // RectangleShape)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Douaa Su
Solution 2