Fetching Movies at App Startup
In this lesson, we cover removing redundant API requests in detail.
We'll cover the following
Introduction
At the moment, fetchMovies()
is being called from the MovieListing
widget’s build
method. A network call is made every time the build
method is called, which can be lots of network operations if the build is triggered often.
Fetching movies at app startup
In this app, we want to fetch movies only once at the start of the application.
We can do so by calling fetchMovies()
from initState()
method.
The initState()
method
initState()
method is called exactly once for each State object it creates, whereas, the build()
method of the Statefulwidget
is called several times during the app’s lifetime.
@override
void initState() {
super.initState();
fetchMovies();
}
The following code snippet shows the change we need to make to _MoviesListingState
class :
class MoviesListing extends StatefulWidget {
@override
_MoviesListingState createState() => _MoviesListingState();
}
class _MoviesListingState extends State<MoviesListing> {
@override
void initState() {
super.initState();
//movies are fetched only once at app’s start-up
fetchMovies();
}
@override
Widget build(BuildContext context) {
fetchMovies(); //move this into initState method
...
}
}
Get hands-on with 1400+ tech skills courses.