【发布时间】:2021-10-22 03:19:06
【问题描述】:
我正在尝试使用sharedPreferences.setString('key', json.encode(myMap)) 检索保存在sharedPreferences 中的Map<String, List<Result>>。
方法toJson() 和fromJson() 已经存在于MyObj 类中。
当我尝试使用json.decode(sharedPreferences.getString('key')) 检索此地图时,我收到错误Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, List<Result>>'
我该如何解决这个问题?
结果类:
class Result {
final String position;
final String points;
final Driver driver
Result({this.position, this.points, this.driver});
factory Result.fromJson(Map<String, dynamic> json) {
return Result(
position: json['position'],
points: json['points'],
driver: Driver.fromJson(json['Driver']),
);
}
Map<String, dynamic> toJson() {
return {
'position': position,
'points': points,
'driver': driver,
};
}
}
sharedPreferences中获取Map的方法:
Future<Map<String, List<Result>>> fetchResult() async {
SharedPreferences sharedPreferences = await getSharedPreferencesInstance();
Map<String, List<Result>> results = Map<String, List<Result>>();
if (sharedPreferences.getString('results') != null) {
results = Map<String, dynamic>.from(json.decode(sharedPreferences.getString('results')));
return results;
} else {
final response = await dio.get(Constants.resultUrl('2021', (i + 1).toString()));
final data = response.data;
List<Result> singleResult = [];
for(...){
for (int j = 0; j <= 19; j++) {
singleResult.add(Result.fromJson(
data['Test']['Table']['Races'][0]['Results'][j]));
}
}
results[data['Test']['Table']['Races'][i]['name']] =
singleResult;
}
sharedPreferences.setString('results', json.encode(results));
return results;
} else {
throw Exception("Fail!");
}
}
}
新错误:
E/flutter ( 4645): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 4645): Receiver: null
E/flutter ( 4645): Tried calling: []("firstName")
firstName 是 Driver 类中的一个字符串。
驱动类:
class Driver {
final String firstName;
final String secondName;
final String dateOfBirth;
final String nationality;
Driver(
{this.firstName,
this.secondName,
this.dateOfBirth,
this.nationality});
factory Driver.fromJson(Map<String, dynamic> json) {
return Driver(
firstName: json['firstName'],
secondName: json['secondName'],
dateOfBirth: json['dateOfBirth'],
nationality: json['nationality'],
);
}
Map<String, dynamic> toJson() {
return {
'firstName': firstName,
'secondName': secondName,
'dateOfBirth': dateOfBirth,
'nationality': nationality,
};
}
【问题讨论】:
-
您好,请在您的帖子中添加一些相关代码。 :)
-
代码添加到问题中
标签: json flutter serialization sharedpreferences deserialization