You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Compose Multiplatform:iOS可加载API图片,Android端加载失败求助

解决Compose Multiplatform Android端图片加载空白问题

1. 给KamelImage添加状态排查逻辑

你当前的KamelImage没有处理加载失败或加载中的状态,空白很可能是加载失败但无提示。修改代码加上状态回调,就能明确问题:

@Composable
fun CarImageCell(image: CarImage) {
    KamelImage(
        asyncPainterResource(image.file),
        contentDescription = image.fileName,
        contentScale = ContentScale.Crop,
        modifier = Modifier.fillMaxWidth().aspectRatio(1.0f),
        onLoading = {
            CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
        },
        onFailure = { exception ->
            Log.e("CarImageLoad", "加载出错: ${exception.message}")
            Text(text = "加载失败")
        }
    )
}

运行后看日志或界面提示,就能知道是加载超时、证书问题还是URL无效。

2. 检查Android网络配置细节

  • 确认AndroidManifest.xml里的INTERNET权限放在<application>标签外,位置不对会不生效:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 你的API域名是loca.lt(本地反向代理),可能存在证书信任问题,需添加网络安全配置:
    在res/xml下新建network_security_config.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">social-pears-camp.loca.lt</domain>
        </domain-config>
    </network-security-config>
    
    然后在AndroidManifest.xml的<application>标签中引用:
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config">
    

3. 验证Ktor HttpClient的Android适配

如果你的httpClient用的是Ktor,Android端必须指定对应引擎:

  • 在Android模块的build.gradle.kts中添加依赖:
    implementation("io.ktor:ktor-client-android:$ktorVersion")
    
  • 初始化Client时指定Android引擎:
    val httpClient = HttpClient(Android) {
        install(ContentNegotiation) {
            json()
        }
        // 其他配置
    }
    

4. 直接验证图片URL可用性

在Android设备的浏览器里打开image.file对应的完整URL,看能不能正常加载图片。如果浏览器也打不开,说明是网络或API的问题,和代码无关。

内容的提问来源于stack exchange,提问作者Semyon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:52:32