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

如何在Android原生Kotlin端读取Flutter shared_preferences存储的字符串列表?

解决Flutter shared_preferences存储的字符串列表在Kotlin中的读取问题

问题原因

Flutter的shared_preferences插件在Android端存储List<String>时,并非直接以原生Set<String>类型存入SharedPreferences,而是将列表序列化为JSON数组字符串后以普通String类型存储。直接调用getStringSet()读取会因类型不匹配触发ClassCastException。

解决步骤

  1. 读取JSON字符串:通过SharedPreferences的getString()方法获取存储的JSON数组字符串。
  2. 解析为字符串列表:使用JSON解析库将JSON字符串转换为List<String>。

示例代码(使用Android内置org.json)

import android.content.Context
import org.json.JSONArray

fun getFlutterStringList(context: Context, key: String): List<String>? {
    val sharedPrefs = context.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)
    val jsonString = sharedPrefs.getString(key, null) ?: return null
    
    return try {
        val jsonArray = JSONArray(jsonString)
        val stringList = mutableListOf<String>()
        for (i in 0 until jsonArray.length()) {
            stringList.add(jsonArray.getString(i))
        }
        stringList
    } catch (e: Exception) {
        // 解析失败时返回null或空列表
        null
    }
}

示例代码(使用Gson)

如果项目已引入Gson依赖,代码更简洁:

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

fun getFlutterStringListWithGson(context: Context, key: String): List<String>? {
    val sharedPrefs = context.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)
    val jsonString = sharedPrefs.getString(key, null) ?: return null
    
    return try {
        val type = object : TypeToken<List<String>>() {}.type
        Gson().fromJson(jsonString, type)
    } catch (e: Exception) {
        null
    }
}

注意事项

  • Flutter的shared_preferences默认使用的SharedPreferences文件名是FlutterSharedPreferences,若Flutter代码自定义了文件名,需替换为对应名称。
  • 确保读取的key与Flutter代码中使用的key完全一致(注意大小写敏感)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:52:43