I'm just studying Flutter and get the following error:
Unhandled Exception: type 'Null' is not a subtype of type 'int'
This is a basic app that fetches some data from an API. Then I would like to show the result in separate cards. It may happen, that some variables will get null because there is no data for this. Eg:(there are no ratings).
This is the class itself:
class Movies {
late int movieId;
late String title;
late String description;
late String date;
late String poster;
late String header;
late double vote;
Movies(
{required this.movieId,
required this.title,
required this.description,
required this.date,
required this.poster,
required this.header,
required this.vote});
Movies.empty();
}
And this is the part where the error is thrown
Connection connection = Connection();
List<Movies> movieTitle = [];
bool loaded = false;
Future<void> createlist() async {
String response = await connection.getMovieByTitle(widget.queryText);
var data = jsonDecode(response);
var results = data['results'];
for (int i = 0; i < results.length; i ) {
movieTitle.add(
Movies(
movieId: data['id'],
title: data['original_title'],
description: data['overview'],
date: data['release_date'],
poster: data['poster_path'],
vote: data['vote_average'],
header: data['backdrop_path']),
);
}
setState(() {
loaded = true;
});
}
What would be the solution?
CodePudding user response:
Make your fields nullable if the API response have null values.
For example: String?
CodePudding user response:
Convert your class to:
class Movies {
int? movieId;
String? title;
String? description;
String? date;
String? poster;
String? header;
double? vote;
Movies({
required this.movieId,
required this.title,
required this.description,
required this.date,
required this.poster,
required this.header,
required this.vote,
});
Movies.empty();
}