JSON DECODE实例
我正在尝试将对象列表保存到共享的偏好中,以易于存储。我会遇到错误[错误:flutter/lib/ui/ui_dart_state.cc(198)]未经手的异常:formatexception:意外字符(在字符1) - > E/Flutter(7980):“历史”的实例
方法
Future<void> recordLocation(lat, long) async {
List<History> histories = [];
final prefs = await SharedPreferences.getInstance();
//fetching history
if (prefs.getStringList('history') != null) {
List<String>? prevHistory = prefs.getStringList('history');
histories = prevHistory!
.map<History>((i) => History.fromJson(json.decode(i)))
.toList();
}
//setting history
History current = History(lat.toString(), long.toString());
histories.add(current);
List<String> newHistory = histories.map((i) => i.toString()).toList();
await prefs.setStringList('history', newHistory);
}
历史模型
class History {
String? latitude;
String? longtitude;
History(this.latitude, this.longtitude);
History.fromJson(Map<String, dynamic> json) {
latitude = json['latitude'];
longtitude = json['longtitude'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['latitude'] = this.latitude;
data['longtitude'] = this.longtitude;
return data;
}
}
I'm trying to save a list of object into a shared preference for easy storage. I'm getting the error [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected character (at character 1) -> E/flutter ( 7980): Instance of 'History'
Method
Future<void> recordLocation(lat, long) async {
List<History> histories = [];
final prefs = await SharedPreferences.getInstance();
//fetching history
if (prefs.getStringList('history') != null) {
List<String>? prevHistory = prefs.getStringList('history');
histories = prevHistory!
.map<History>((i) => History.fromJson(json.decode(i)))
.toList();
}
//setting history
History current = History(lat.toString(), long.toString());
histories.add(current);
List<String> newHistory = histories.map((i) => i.toString()).toList();
await prefs.setStringList('history', newHistory);
}
History model
class History {
String? latitude;
String? longtitude;
History(this.latitude, this.longtitude);
History.fromJson(Map<String, dynamic> json) {
latitude = json['latitude'];
longtitude = json['longtitude'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['latitude'] = this.latitude;
data['longtitude'] = this.longtitude;
return data;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
人们通常将
FromJSON
方法声明为工厂方法,而数据类则不可变。而是尝试一下:People usually declare the
fromJson
method as a factory method and data classes as immutable. Try this instead:编辑:
我已经在DARTPAD中运行了此代码,并且输出为:
问题在于字符串转换为映射&lt; string,dynamic&gt;
编辑2:
在这里,如果您不想更改您的历史课,则只需在ToString()方法中进行编辑:
Edit:
I have run this code in dartpad and it gives the output as:
The problem was with the conversion of string to Map<String, dynamic>
Edit 2:
Here if you do not want to change your history class then just make edit in the toString() method: