skip to Main Content

I want to fetch and format json data from this as a trial in flutter. However, during the formatting process, an exception occurs: type 'Null' is not a subtype of type 'String'.

And these are my code:

user_model.dart

class User {
  int    id;
  String email;
  String firstName;
  String lastName;
  String avator;
  User({
    required this.id,
    required this.email,
    required this.firstName,
    required this.lastName,
    required this.avator
  });

  factory User.fromJson(Map<String, dynamic> json) => User(
    id        : json['id'],
    email     : json['email'],
    firstName : json['first_name'],
    lastName  : json['last_name'],
    avator    : json['avator']
  );
}

user_api.dart

...
class UserApi {
  Future<List<User>?> getUsers() async {
    final url = Uri.parse('https://reqres.in/api/users?page=2');
    try {
      final res = await http.get(url);
      if (res.statusCode == 200) {
        final Map<String, dynamic> body  = jsonDecode(res.body);
        final List<User> users = body['data'].map((dynamic userData) => {
          print('userData : $userData');
          User.fromJson(userData) // There seems to be an error here.
        }).toList();
        return users;
      } else {
        return null;
      }
    } catch (e) {
      print(e.toString());
    }
    return null;
  }
}

And userData seems like this in my console:

flutter: userData : {id: 7, email: [email protected], first_name: Michael, last_name: Lawson, avatar: https://reqres.in/img/faces/7-image.jpg}

I don’t think userData is kind of Null, but why do I get the exception?

3

Answers


  1. You need to use json['avatar'] instead of json['avator']

    factory User.fromJson(Map<String, dynamic> json) => User(
        id        : json['id'],
        email     : json['email'],
        firstName : json['first_name'],
        lastName  : json['last_name'],
        avator    : json['avatar'] //here `a` instead of `o`
      );
    
    Login or Signup to reply.
  2. I just checked the link you have mentioned for the json you are using. There is a typo at your end. In the json, avatar is the correct field spelling. You have mentioned avator in your class’s factory constructor.

    So, avator is Null and thus, String avator is assigned to a Null value.

    FYI: The error type 'Null' is not a subtype of type 'String' means that you are trying to assign a Null value to a String type variable.

    Login or Signup to reply.
  3. its a typo in the fromJson method : as mentioned by yeasin-sheikh (You need to use json[‘avatar’] instead of json[‘avator’]),
    Yeasin-sheikh’s answer

    there are some json parsing websites, using that we can easily generate model class and other methods related to it.

    eg : app.quicktype.io

    just input the json response and generate the model class in required language.

    sample image

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search