1

我的摇篮

// Coil
implementation "io.coil-kt:coil-compose:1.4.0"

问题描述

以前我将线圈与 Google 一起使用accompanist,但是当我迁移到新版本的线圈时,如文档所示,我遇到了该target方法的问题:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.pokedex, PID: 13502
    java.lang.IllegalArgumentException: request.target must be null.
        at coil.compose.ImagePainterKt.rememberImagePainter(ImagePainter.kt:94)
...

线圈实现

在浏览(线圈类)的内部代码时,ImagePainter您可以看到由于target某种原因该方法确实需要为空:

@Composable
fun rememberImagePainter(
     request: ImageRequest,
     imageLoader: ImageLoader,
     onExecute: ExecuteCallback = ExecuteCallback.Default,
): ImagePainter {
     requireSupportedData(request.data)
     require(request.target == null) { "request.target must be null." }
...

我的代码

这是我在 jetpack compose 中的组件(图像组件位于列内):

Image(
    modifier = Modifier
        .size(120.dp)
        .align(Alignment.CenterHorizontally),
    painter = rememberImagePainter(
        data = entry.imageUrl,
        builder = {
            crossfade(true)
            target {
                viewModel.calcDominantColor(it) { color ->
                    dominantColor = color
                }
            }
            transformations(CircleCropTransformation())
        },
    ),
    contentDescription = entry.pokemonName
)

viewModel我需要目标方法根据drawable它作为参数传递来对我进行内部操作。有人能帮我吗?

4

1 回答 1

4

这是预期的行为,因为rememberImagePaintertarget内部设置。

您可以跟踪画家状态,等待Success并从中获取drawable。也可以使用它LaunchedEffect来防止重新计算:

val painter = rememberImagePainter(
    data = imageUrl,
    builder = {
        ...
    },
)
(painter.state as? ImagePainter.State.Success)
    ?.let { successState ->
        LaunchedEffect(Unit) {
            val drawable = successState.result.drawable
            viewModel.calcDominantColor(drawable) { color ->
                dominantColor = color
            }
        }
    }
Image(
    painter = painter,
    contentDescription = "...",
    modifier = Modifier
        ...
)
于 2021-11-03T02:12:15.167 回答