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

Jetpack Compose中SnapshotStateList无法保存,求自定义Saver实现方案

问题解决:SnapshotStateList无法通过rememberSaveable保存

报错信息

java.lang.IllegalArgumentException: compose.runtime.snapshots.SnapshotStateList@430cd20 cannot be saved using the current SaveableStateRegistry

问题根源

mutableStateListOf创建的SnapshotStateList对象,默认没有内置的序列化/反序列化逻辑,rememberSaveable无法自动处理它的状态保存,因此触发报错。

解决方案

为SnapshotStateList<Course>实现自定义Saver,并在rememberSaveable中指定使用该Saver。

1. 编写自定义Saver

创建针对SnapshotStateList<Course>的Saver,核心逻辑是将可变状态列表转为普通List保存,恢复时再转回可变状态列表:

val snapshotStateListSaver = Saver<SnapshotStateList<Course>, List<Course>>(
    save = { it.toList() },
    restore = { mutableStateListOf<Course>().apply { addAll(it) } }
)

2. 修改变量定义

将原来的rememberSaveable调用替换为指定自定义Saver的版本:

val starters = rememberSaveable(saver = snapshotStateListSaver) { mutableStateListOf<Course>() }
val firstcourses = rememberSaveable(saver = snapshotStateListSaver) { mutableStateListOf<Course>() }
val secondcourses = rememberSaveable(saver = snapshotStateListSaver) { mutableStateListOf<Course>() }
val sides = rememberSaveable(saver = snapshotStateListSaver) { mutableStateListOf<Course>() }
val fruits = rememberSaveable(saver = snapshotStateListSaver) { mutableStateListOf<Course>() }
val desserts = rememberSaveable(saver = snapshotStateListSaver) { mutableStateListOf<Course>() }
val drinks = rememberSaveable(saver = snapshotStateListSaver) { mutableStateListOf<Course>() }

3. 确保Course类可序列化

如果Course是自定义数据类,必须让它支持序列化,否则转成普通List后依然无法保存。两种常见实现方式:

  • 实现Serializable接口:
data class Course(/* 你的字段定义 */) : Serializable
  • 使用@Parcelize实现Parcelable(需在Gradle中添加Parcelize依赖):
@Parcelize
data class Course(/* 你的字段定义 */) : Parcelable

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:46:07