如何在Android原生Kotlin端读取Flutter shared_preferences存储的字符串列表?
问题原因
Flutter的shared_preferences插件在Android端存储List<String>时,并非直接以原生Set<String>类型存入SharedPreferences,而是将列表序列化为JSON数组字符串后以普通String类型存储。直接调用getStringSet()读取会因类型不匹配触发ClassCastException。
解决步骤
- 读取JSON字符串:通过SharedPreferences的
getString()方法获取存储的JSON数组字符串。 - 解析为字符串列表:使用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
相关产品推荐
相关产品推荐

