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

Flutter调用API时出现NoSuchMethodError(map调用在null上)求助

Flutter API获取数据报错:NoSuchMethodError: The method 'map' was called on null

报错信息

NoSuchMethodError : The method 'map' was called on null.
Receiver: null
Tried calling : map(closure => (dynamic) => Product)

问题代码

API响应处理代码

Future<ApiResponse> getProducts() async {
  ApiResponse apiResponse = ApiResponse();
  try {
    String token = await getToken();
    final response = await http.get(Uri.parse(productURL),
    headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    });

    switch(response.statusCode){
      case 200:
        apiResponse.data = jsonDecode(response.body)['products'].map((p) => Product.fromJson(p)).toList();
        apiResponse.data as List<dynamic>;
        break;
      case 401:
        apiResponse.error = unauthorized;
        break;
      default:
        apiResponse.error = somethingWentWrong;
        break;
    }
  }
  catch (e){
    apiResponse.error = e.toString();
  }
  return apiResponse;
}

Product模型代码

class Product {
  int? id;
  String? name;
  String? price;
  String? stock;
  String? type;
  String? description;
  String? image;
  String? likesCount;
  String? commentsCount;
  User? user;
  bool? selfLiked;

  Product({
    this.id,
    this.name,
    this.price,
    this.stock,
    this.type,
    this.description,
    this.image,
    this.likesCount,
    this.commentsCount,
    this.user,
    this.selfLiked,
  });

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['id'],
      name: json['name'],
      price: json['price'],
      stock: json['stock'],
      type: json['type'],
      description: json['description'],
      image: json['image'],
      likesCount: json['likes_count'],
      commentsCount: json['comments_count'],
      selfLiked: json['likes'].length > 0,
      user: User(
        id: json['user']['id'],
        name: json['user']['name'],
        image: json['user']['image'],
      ),
    );
  }
}

问题原因

这个错误的核心是jsonDecode(response.body)['products']返回了null,你直接调用了map方法。可能的场景包括:

  • API返回的JSON结构里没有products这个键
  • API返回的products字段值就是null(比如没有产品数据时)
  • 你对API返回结构的预期和实际返回不匹配

修复方案

1. 先验证API返回的实际内容

在case 200分支里先打印返回的JSON,确认结构是否符合预期:

case 200:
  print(jsonDecode(response.body)); // 打印完整响应内容
  // ... 后续代码

通过打印可以明确products字段是否存在、是否为数组。

2. 给products字段加空安全判断

修改API处理代码,先检查products是否为null,再执行map转换:

case 200:
  final responseJson = jsonDecode(response.body);
  final productsList = responseJson['products'];
  // 处理products为null的情况,避免调用map报错
  if (productsList != null) {
    apiResponse.data = productsList.map((p) => Product.fromJson(p)).toList();
  } else {
    // 可以设置为空列表,或者自定义错误信息
    apiResponse.data = [];
    // apiResponse.error = '未获取到产品数据';
  }
  break;

3. 修复Product模型里的潜在空安全问题

你的Product.fromJson里还有两处可能触发空指针的地方:

  • json['likes'].length:如果likes字段为null,调用length会报错
  • json['user']['id']:如果user字段为null,直接访问子属性会报错

修改后的fromJson方法:

factory Product.fromJson(Map<String, dynamic> json) {
  final likes = json['likes'] as List?;
  final userJson = json['user'] as Map<String, dynamic>?;
  
  return Product(
    id: json['id'],
    name: json['name'],
    price: json['price'],
    stock: json['stock'],
    type: json['type'],
    description: json['description'],
    image: json['image'],
    likesCount: json['likes_count'],
    commentsCount: json['comments_count'],
    selfLiked: likes?.length ?? 0 > 0,
    user: userJson != null 
        ? User(
            id: userJson['id'],
            name: userJson['name'],
            image: userJson['image'],
          )
        : null,
  );
}

额外建议

  • 在使用apiResponse.data的时候,最好也做一层空判断,比如:
    final products = apiResponse.data ?? [];
    
    这样后续遍历或展示数据时不会因为null出现问题。
  • 可以使用json_serializable包来自动生成模型的fromJson方法,减少手动编写的错误。

内容的提问来源于stack exchange,提问作者Fawwaz Saputra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:46:03