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
You need to use
json['avatar']
instead ofjson['avator']
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 mentionedavator
in your class’s factory constructor.So,
avator
isNull
and thus,String avator
is assigned to aNull
value.FYI: The error
type 'Null' is not a subtype of type 'String'
means that you are trying to assign aNull
value to aString
type variable.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.