【问题标题】:flutter error while trying to retrieve a Map from sharedPreferences尝试从 sharedPreferences 检索地图时出现颤振错误
【发布时间】: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


【解决方案1】:

更改此代码:

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'])

【讨论】:

  • 好吧,它似乎工作。现在我有一个新错误,(我用新错误更新了问题),它与驱动程序类有关。
  • 添加您的驱动程序类和问题中出现错误的代码
  • 你在哪里打电话firstName
  • 我认为是 Result.fromJson() 包含驱动程序:Driver.fromJson()
  • 我已经编辑了我的答案。如果您的错误发生,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2019-07-20
  • 2022-08-18
  • 2021-12-24
  • 1970-01-01
  • 2020-04-15
  • 2022-11-04
  • 2022-07-07
  • 1970-01-01
相关资源
最近更新 更多