首页 > 解决方案 > 在 null 上调用了方法“map”。扑

问题描述

我正在尝试从 Json 获取用户,但不知何故我收到错误消息

the method 'map' was called on null. flutter

我不知道为什么,这是我的模型代码:

class User {

  final String id;
  final String email;
  final String username;
   List<FollowUserModel> following = [];
   List<FollowUserModel> followers = [];
  
  User({this.id,this.email,this.followers,this.following, this.username});

  factory User.fromJSON(Map<String, dynamic> jsonMap) {

    return User(
      id: jsonMap['id'] as String,
      email: jsonMap['email'] as String,
       username: jsonMap['username'] as String,
      following: jsonMap["following_set"] != null ? List<FollowUserModel>.from( jsonMap["followiing_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
      followers: jsonMap["followers_set"] != null ? List<FollowUserModel>.from( jsonMap["followers_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
     );
  }
}

class FollowUserModel {
  final String id;
  final User author;
  final User profile;


  FollowUserModel({this.id,this.author,this.profile});


  factory  FollowUserModel.fromJSON(Map<String, dynamic> jsonMap) {
    return  FollowUserModel(
      id: jsonMap['id'] as String,
      author: jsonMap['author'] as User,
      profile: jsonMap['profile'] as User,
    );
  }



}

这是我的异常中的完整错误代码: 异常代码

我之前将数组声明为 [],因为我希望返回一些空值,但仍然出现错误。有人知道原因吗?

更新 我知道我打错了,但错误仍然存​​在。

标签: flutterdart

解决方案


你打错了,而不是 'following_set' 和 'followers_set' 你写的是 'followiing_set' 和 'followrse_set':

.... 
following: jsonMap["following_set"] != null ? List<FollowUserModel>.from( jsonMap["followiing_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
followers: jsonMap["followers_set"] != null ? List<FollowUserModel>.from( jsonMap["followrse_set"].map((x) => FollowUserModel.fromJSON(x))) :[],
....

推荐阅读