You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter接口JSON序列化失败:NoSuchMethodError异常求助

解决NoSuchMethodError: map被调用在null上的序列化问题

我帮你排查出几个关键问题,一步步来修正:

1. JSON字段名不匹配(核心错误)

你的API返回的数组字段是"location",但在Details.fromJson里你尝试读取的是parsedJson['locations'](多了个s),这直接导致list变量为null,调用map时就会抛出那个错误。

修正Model类的fromJson方法:

factory Details.fromJson(Map<String, dynamic> parsedJson) {
  // 把'locations'改成'location',和API返回的字段名一致
  var list = parsedJson['location'] as List?;
  // 加个空值处理,避免list为null时调用map
  List<Location> locationList = list?.map((i) => Location.fromJson(i)).toList() ?? [];
  return Details(
    username: parsedJson['username'],
    locations: locationList
  );
}

2. API返回的JSON存在语法错误

第二个对象的location数组里,最后一个元素后面多了个逗号,虽然部分JSON解析器能兼容,但这不符合标准JSON语法,建议后端修正:

原错误片段:

{ "latitude": "34222", "longitude": "32243" },

修正后:

{ "latitude": "34222", "longitude": "32243" }

3. 优化Model类的健壮性

  • 给Location的构造函数添加required修饰符,确保必填参数不会为null:
class Location {
  final String latitude;
  final String longitude;
  // 添加required
  Location({required this.latitude, required this.longitude});

  factory Location.fromJson(Map<String, dynamic> parsedJson) {
    return Location(
      latitude: parsedJson['latitude'],
      longitude: parsedJson['longitude']
    );
  }

  // 添加toString方便调试打印
  @override
  String toString() => 'Location(latitude: $latitude, longitude: $longitude)';
}
  • 给Details类也添加toString方法,方便你打印查看数据:
class Details {
  final String? username;
  final List<Location> locations;
  Details({this.username, required this.locations});

  factory Details.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['location'] as List?;
    List<Location> locationList = list?.map((i) => Location.fromJson(i)).toList() ?? [];
    return Details(
      username: parsedJson['username'],
      locations: locationList
    );
  }

  @override
  String toString() => 'Details(username: $username, locations: $locations)';
}

4. 优化API请求函数的处理

如果你的API返回的是多个Details对象的数组,建议把整个列表都解析出来,而不是只取第一个元素:

Future<void> showLocation() async {
  var response = await http.get(Uri.encodeFull(url1));
  if (response.statusCode == 200) {
    print(response.body);
    final data = json.decode(response.body) as List;
    // 解析整个列表
    List<Details> detailsList = data.map((item) => Details.fromJson(item)).toList();
    print(detailsList);
  } else {
    throw Exception('failed to load');
  }
}

这样修改后,你的序列化逻辑就能正常工作,不会再抛出那个null调用map的错误了。

内容的提问来源于stack exchange,提问作者Rajashree Parhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:25:26