I tried a tutorial to create a movie application. It works fine to get popular movies but with the same code to get upcoming movies I got this error and UI doesn't show anything. The error is : Expected a value of type 'String', but got one of type 'Null'
here is where error happens:
Future<List<Movie>> getPopularMovies({required int page}) async {
//we are going to get Response
Response _response =
await _http.request('/movie/popular', query: {'page': page});
if (_response.statusCode == 200) {
Map<String?, dynamic> _data = _response.data;
List<Movie> _movies = _data['results'].map<Movie>((_movieData) {
return Movie.fromJson(_movieData);
}).toList();
return _movies;
} else {
throw Exception('Couldn\'t get the popular movies');
}
}
Future<List<Movie>> getUpcomingMovies({required int page}) async {
//we are going to get Response
Response _response =
await _http.request('/movie/upcoming', query: {'page': page});
if (_response.statusCode == 200) {
Map<String?, dynamic> _data = _response.data;
List<Movie> _movies = _data['results'].map<Movie>((_movieData) {
return Movie.fromJson(_movieData);
}).toList();
return _movies;
} else {
throw Exception('Couldn\'t get the popular movies');
}
}
I tried jsonDecode(_response.data)
but got the this error: Expected a value of type 'String', but got one of type '_JsonMap'
CodePudding user response:
Maybe some particular field in your model class may receive null value from response...that's why flutter indicates error....
To avoid this you have to make the field nullable using (?)...
Example:
int? rank;
Inside constructor remove required keyword for that field.
Now it will accepts null values...
CodePudding user response:
Can solve your problem
Future<List<Movie>> getUpcomingMovies({required int page}) async {
List<Movie> list = [];
Response _response = http
.request('/movie/upcoming', query: {'page': page})
.then((_response) {
setState(() {
var list = json.decode(_response.body);
//categories = list.map((category) => Category.fromJson(category)).toList();
if (list is List) {
Map<String?, dynamic> _data = _response.data;
List<Movie> _movies = _data['results'].map<Movie>((_movieData) {
return Movie.fromJson(_movieData);
}).toList();
return _movies;
}
else {
print('response is not list');
}
});
}
);
return list;
}