Modularizing Code
In this lesson, we cover the organizing code for better readability in detail.
We'll cover the following
This lesson delves further into executing HTTP requests to fetch movie data and organize code for better readability.
Modularizing code
Let’s move the getJson()
method in its own class, say MoviesProvider
. This keeps related code together.
All images in TMDB are hosted in a common location. We’ll use the imagePathPrefix
variable to hold this path in the MoviesProvider
class. Since this path doesn’t change and should be accessible from other classes, it should be final
and static
.
The imagePathPrefix
is the path to image storage. Each movie carries its own unique poster path in the poster_path
attribute. Combining the value of imagePathPrefix
and poster_path
will give the full path for the image resource.
class MoviesProvider {
static final String imagePathPrefix = 'https://image.tmdb.org/t/p/w500/';
static Future<Map> getJson() async {
//API Key. Don't forget to replace it with your own key.
final apiKey = "YOUR_API_KEY";
//URL to fetch movies by their popularity
final apiEndPoint =
"http://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&sort_by=popularity.desc";
//Response returned from API/Server
final apiResponse = await http.get(apiEndPoint);
//Parsing to JSON using dart:convert
return json.decode(apiResponse.body);
}
}
Get hands-on with 1400+ tech skills courses.