【问题标题】:Unhandled Exception: type 'int' is not a subtype of type 'List<int>' in type cast未处理的异常:类型“int”不是类型转换中“List<int>”类型的子类型
【发布时间】:2021-11-28 09:53:32
【问题描述】:

我正在尝试序列化一个类,以便可以将其保存在共享首选项中。对于序列化,我使用 Flutter 的 JsonSerializable 包。

我生成的代码如下所示:

class calculation {
  List<int>? calcs;
  List<int>? results;
  List<int>? selectedSpots;
  List<double>? linedataX;
  List<double>? linedataY;
  Map<int, List<int>>? someMap;



  calculation({
    this.calcs,
    this.results,
    this.selectedSpots,
    this.linedataX,
    this.linedataY,
    this.someMap,

  });




  factory calculation.fromJson(Map<String, dynamic> jsonData) {
    return calculation(
      calcs: jsonData['calcs'].cast<int>(),
      results: jsonData['results'].cast<int>(),
      selectedSpots: jsonData['selectedSpots'].cast<int>(),
      linedataX: jsonData['linedataX'].cast<double>(),
      linedataY: jsonData['linedataY'].cast<double>(),
      someMap: (jsonData['someMap'] as Map?)?.map(
            (k, e) => MapEntry(int.parse(k as String),  e as List<int>  ),
      ),

    );
  }

  static Map<String, dynamic> toMap(calculation calc) => {
        'calcs': calc.calcs,
        'results': calc.results,
        'selectedSpots': calc.selectedSpots,
        'linedataX': calc.linedataX,
        'linedataY': calc.linedataY,
    'someMap': calc.someMap?.map((k, e) => MapEntry(k.toString(), e)),

  }; 

只有当我的地图是 Map?.

时才会出现错误

Map? 工作正常。

知道如何正确投射到列表吗?

【问题讨论】:

  • 如果你有一个 JSON 响应,你可以试试这个 [javiercbk.github.io/json_to_dart/] 这会给你一个非常好的格式。所以你不需要自己做正确的事情,也不会出现这种类型的错误。

标签: json flutter serialization sharedpreferences


【解决方案1】:

尝试改变这一点

calcs: jsonData['calcs'].cast<int>(),
results: jsonData['results'].cast<int>(),
selectedSpots: jsonData['selectedSpots'].cast<int>(),

到这里:

calcs: jsonData['calcs'].cast<List<int>>(),
results: jsonData['results'].cast<List<int>>(),
selectedSpots: jsonData['selectedSpots'].cast<List<int>>(),

现在投射到一个列表

【讨论】:

    【解决方案2】:

    通过使用自定义对象而不是地图来解决它。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多