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

Flutter开发中如何在Shared Preferences中存储List<List<String>>类型数据?

Flutter使用shared_preferences存储二维字符串列表的实现方案

shared_preferences插件本身仅支持存储一维List<String>类型数据,无法直接存储嵌套的字符串列表结构,以下是两种可直接落地的实现方式:

方案1:扁平化拼接存储

该方案实现简单、性能开销小,需注意选择的分隔符不能出现在你要存储的字符串内容中:

  • 存储逻辑:
import 'package:shared_preferences/shared_preferences.dart';

// 待存储的二维字符串列表
List<List<String>> originalData = [
  ["str1", "str2"],
  ["str3", "str4"]
];

// 将每个子列表用特殊分隔符拼接为单个字符串,组成一维列表
const separator = '#||#'; // 可自定义为不会出现在业务字符串中的字符
List<String> flatList = originalData.map((subList) => subList.join(separator)).toList();

// 写入存储
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('your_storage_key', flatList);
  • 读取还原逻辑:
final prefs = await SharedPreferences.getInstance();
List<String>? storedFlatList = prefs.getStringList('your_storage_key');

// 还原为二维列表
const separator = '#||#';
List<List<String>> restoredData = storedFlatList?.map((item) => item.split(separator)).toList() ?? [];

方案2:JSON序列化存储

该方案为通用解决方案,无需考虑字符串内容冲突问题,兼容性更强:

  • 存储逻辑:
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

List<List<String>> originalData = [
  ["str1", "str2"],
  ["str3", "str4"]
];

// 直接将整个二维列表序列化为JSON字符串
String jsonStr = jsonEncode(originalData);

// 写入存储
final prefs = await SharedPreferences.getInstance();
await prefs.setString('your_storage_key', jsonStr);
  • 读取还原逻辑:
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

final prefs = await SharedPreferences.getInstance();
String? storedJson = prefs.getString('your_storage_key');

// 还原为二维列表
List<List<String>> restoredData = [];
if (storedJson != null) {
  List<dynamic> tempList = jsonDecode(storedJson);
  restoredData = tempList.map((subItem) => List<String>.from(subItem)).toList();
}

内容的提问来源于stack exchange,提问作者Ali F. Abbas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:00:01