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

如何让rememberSaveable支持Map<String, Boolean>状态的保存与恢复?

解决rememberSaveable无法保存Map状态的问题

问题根源

rememberSaveable 默认仅支持可自动序列化的类型(如基本类型、Parcelable、Serializable),你当前使用的 Map<String, Boolean> 没有内置的状态保存器(Saver),因此无法完成状态的持久化与恢复。

可行解决方案

方案1:自定义状态保存器(Saver)

手动实现Map的序列化与反序列化逻辑,这是最灵活的方式:

var state by rememberSaveable(
    saver = mapSaver(
        // 将Map转换为可保存的键值对列表
        save = { map -> map.entries.map { it.key to it.value } },
        // 从键值对列表恢复为Map
        restore = { pairList -> pairList.toMap().toMutableMap() }
    )
) {
    mutableStateOf(
        enumValues<NavigationItem>().associate { it.route to true }.toMutableMap()
    )
}

方案2:改用Serializable类型的Map

HashMap 实现了 Serializable 接口,直接将初始Map转为HashMap即可让rememberSaveable自动处理:

var state by rememberSaveable {
    mutableStateOf(
        hashMapOf(*enumValues<NavigationItem>().associate { it.route to true }.entries.toTypedArray())
    )
}

方案3:用Serializable数据类包裹状态

将状态封装到实现Serializable的数据类中,让rememberSaveable自动识别处理:

data class NavigationState(val routeStates: Map<String, Boolean>) : Serializable

var state by rememberSaveable {
    mutableStateOf(
        NavigationState(enumValues<NavigationItem>().associate { it.route to true })
    )
}
// 使用时通过 state.value.routeStates 访问状态

额外优化建议

如果后续仅会修改部分路由的状态(比如只有少数路由会被设为false),可以只保存状态有变化的路由键值对,减少持久化的数据量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:57:23