【发布时间】:2021-06-04 05:09:55
【问题描述】:
我已经解码了我的response.body 即var jsonData = jsonDecode(response.body); 并且它工作正常
但是当我像这样使用sharedpref将它转换成对象并保存到本地存储中时
if (response.statusCode == 200) {
jsonData['categoryList'].forEach((data) => {
categoryList.add(new ExpertCategory(
id: jsonData['_id'],
color: jsonData['color'],
type: jsonData['category_name'],
icon: ":)"))
});
print(categoryList) ;
localStorage.setCategoryData(categoryList.toString());
它存储在其中每当我尝试对其进行解码时,它都无法正常工作,即
localStorage.getCategoryData().then((data) => {
userMap = jsonDecode(data),
});
class LocalStorage {
Future setCategoryData(data) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString('category', data);
}
Future getCategoryData() async {
final prefs = await SharedPreferences.getInstance();
final category = prefs.getString('category');
return category;
}
}
import 'package:flutter/foundation.dart';
class ExpertCategory {
final String id;
final String type;
final String icon;
final String color;
const ExpertCategory( {
@required this.id,
@required this.type,
@required this.icon,
@required this.color,
});
}
它与以前不同,它显示错误并且在修复字符串'['的一些第一个元素之后 正在显示。请提前帮助解决这个问题。
【问题讨论】:
-
您遇到的错误是什么?还可以在通过 jsonDecode 传递变量之前尝试打印变量的类型,以确保它实际上是字符串,data.runtimeType 参考:programming-idioms.org/idiom/94/print-type-of-variable/2210/… 如果是字符串,请尝试打印它,确保它是有效的 json
-
请分享您的 localStorage 类的完整代码,显示您用于存储数据的方法以及如何检索它们。
-
@AliAlNoaimi userMap = jsonEncode(data), userMap1 = jsonDecode(userMap), print(userMap1[0]), I/flutter (25831): [如果我在该函数下执行此操作 userMap1 = jsonDecode (数据),打印(userMap1 [0]),给出这个[错误:flutter/lib/ui/ui_dart_state.cc(177)]未处理的异常:FormatException:意外字符(在字符2处)E/flutter(25831):[ “ExpertCategory”实例、“ExpertCategory”实例、“E..”实例
-
@Omotayo4i 我已经编辑了我的问题。
-
@JayParmar 提供ExpertCategory类的完整代码
标签: json flutter sharedpreferences jsondecoder