尝试从 sharedPreferences 检索地图时出现颤动错误

flutter error while trying to retrieve a Map from sharedPreferences

我正在尝试使用 sharedPreferences.setString('key', json.encode(myMap)) 检索保存在 sharedPreferences 中的 Map<String, List<Result>>
方法 toJson()fromJson() 已经存在于 MyObj 中class.
当我尝试使用 json.decode(sharedPreferences.getString('key')) 检索此地图时,出现错误 Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, List<Result>>'

我该如何解决这个问题?

结果class:

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 中检索地图的方法:

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 class:

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,
    };
  }

更改此代码:

results = Map<String, dynamic>.from(json.decode(sharedPreferences.getString('results')));
return results;

为此:

final decodedJson = Map<String, List<dynamic>>.from(json.decode(sharedPreferences.getString('results')));

for (var entry in decodedJson.entries) {
  final resultList = <Result>[];
  for (var eachResult in entry.value) {
    resultList.add(Result.fromJson(eachResult));
  }
  results[entry.key] = resultList;
}

return results;

新错误的解决方法: 您在 Result.fromJson() 构造函数中拼错了 json 参数的键。 它应该是 Driver.fromJson(json['driver']) 而不是 Driver.fromJson(json['Driver']).