Flutter如何匹配JSON的sendto_id与SharedPreferences存储ID实现计数
代码修改点
- 调整异步执行顺序:避免网络请求先于本地id读取完成,导致匹配失效
- 新增条目过滤逻辑:仅统计
sendto_id与本地存储id匹配的条目数量
关键代码调整片段
1. 修改getPref方法
拿到本地存储的id后再发起网络请求,增加空值兜底防止类型报错:
getPref() async { SharedPreferences preferences = await SharedPreferences.getInstance(); // 空值兜底,取不到id时默认赋值为空字符串,避免匹配时出现null报错 id = preferences.getString('id') ?? ''; // 保证id赋值完成后再请求接口,避免匹配时id未初始化 getData(); }
2. 修改getData方法内的计数逻辑
替换原来直接取整个返回列表长度的写法,新增匹配过滤:
Future getData() async { var url = 'http://10.20.35.1/school/fetch2.php'; http.Response response = await http.get(url); List data = json.decode(response.body); // 过滤出sendto_id与本地id相等的条目,统计匹配数量 int matchedCount = data.where((item) => item['sendto_id'] == id).length; setState(() { counter = matchedCount; }); }
3. 修改initState
无需同时调用两个异步方法,仅触发getPref即可:
@override void initState() { super.initState(); getPref(); }
补充说明
- 示例中
sendto_id和SharedPreferences存储的id均为String类型,可直接比对,无需额外类型转换 - 若实际使用中出现类型不匹配问题(比如一方是数字、一方是字符串),可统一转成字符串再比对:
item['sendto_id'].toString() == id
内容的提问来源于stack exchange,提问作者Ren Rhen
相关产品推荐
相关产品推荐

