如何在Flutter的shared_preferences中创建布尔列表并存储布尔值
解决方案
shared_preferences没有提供直接存储List<bool>的原生API,有两种常用实现方案可以满足你的需求:
方案1:将布尔列表转为字符串列表存储
这种方案适合需要一次性读写整个布尔列表的场景,实现逻辑如下:
存储示例代码
Future<void> saveFavoriteList(List<bool> favoriteList) async { SharedPreferences prefs = await SharedPreferences.getInstance(); // 把bool列表转成String列表 List<String> strList = favoriteList.map((bool value) => value.toString()).toList(); await prefs.setStringList('favorite_all', strList); }
读取示例代码
Future<List<bool>> loadFavoriteList() async { SharedPreferences prefs = await SharedPreferences.getInstance(); List<String>? strList = prefs.getStringList('favorite_all'); // 空值处理,默认返回全false的列表,长度可以按你的实际需求调整 if (strList == null) return List.generate(100, (index) => false); return strList.map((String str) => str == 'true').toList(); }
方案2:按索引拼接唯一key单独存储
这种方案更适配你当前用PageView的场景,修改单个索引的收藏状态时不需要更新整个列表,性能更高,你现有的代码稍作调整就能用:
封装通用操作方法
// 读取指定索引的收藏状态 Future<bool> getFavoriteByIndex(int index) async { SharedPreferences prefs = await SharedPreferences.getInstance(); // 空值默认返回false return prefs.getBool('favorite_$index') ?? false; } // 保存指定索引的收藏状态 Future<void> setFavoriteByIndex(int index, bool value) async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setBool('favorite_$index', value); } // 切换指定索引的收藏状态 Future<void> toggleFavoriteByIndex(int index) async { bool current = await getFavoriteByIndex(index); await setFavoriteByIndex(index, !current); }
调用示例
// 加载指定索引的收藏状态 loadFavorite() async { setState(() { favorite[index] = await getFavoriteByIndex(index); }); } // 点击收藏按钮时调用 onTapFavorite() async { await toggleFavoriteByIndex(index); setState(() { favorite[index] = !favorite[index]; }); }
内容的提问来源于stack exchange,提问作者eno2
相关产品推荐
相关产品推荐

