如何在jetpack compose的新线圈版本中使用“ImageRequest.Builder.target”?

Pie*_*ira 3 crash android android-jetpack-compose coil

我的摇篮

// Coil
implementation "io.coil-kt:coil-compose:1.4.0"
Run Code Online (Sandbox Code Playgroud)

问题描述

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

// Coil
implementation "io.coil-kt:coil-compose:1.4.0"
Run Code Online (Sandbox Code Playgroud)

线圈实施

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

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)
...
Run Code Online (Sandbox Code Playgroud)

我的代码

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

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

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

Phi*_*hov 5

在 Coil 2.0.0中,AsyncImagerememberAsyncImagePainter都有onSuccess回调参数,使用它你可以如下获取可绘制对象:

AsyncImage(
    model = imageURL,
    contentDescription = null,
    onSuccess = { success ->
        val drawable = success.result.drawable
    }
)
Run Code Online (Sandbox Code Playgroud)

线圈1.4.0版本:

这是预期的行为,因为在内部rememberImagePainter设置了target

您可以跟踪画家状态,等待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
        ...
)
Run Code Online (Sandbox Code Playgroud)


小智 5

我知道您遵循 Philipp Lackner 的https://www.youtube.com/watch?v=jrIfGAk8PyQ&list=PLQkwcJG4YTCTimTCpEL5FZgaWdIZQuB7m&index=5尝试此代码

AsyncImage(
            model = ImageRequest.Builder(LocalContext.current)
                .data(entry.imageUrl)
                .crossfade(true)
                .build(),
            contentDescription = entry.pokemonName,
            onSuccess = {
                viewModel.calcDominantColor(it.result.drawable) { color ->
                    dominantColor = color
                }
            },
            modifier = Modifier
                .size(120.dp)
                .align(CenterHorizontally)
        )
Run Code Online (Sandbox Code Playgroud)

并使用此库实现(“io.coil-kt:coil-compose:2.2.2”)和更多信息https://coil-kt.github.io/coil/compose/