Converting API Response to MovieModel List

In this lesson, you'll learn to use the "MovieModel" object to build a "movies" list of movie entries returned from the API response.

Converting JSON to MovieModel object

You’ll convert the API response to MovieModel objects before adding to the movies list.

//List of movies to hold data parsed from api response
List<MovieModel> movies = List<MovieModel>();

fetchMovies() async {

// Fetching data from server
 var data = await MoviesProvider.getJson();

 setState(() {
//Holding data from server in generic list results
   List<dynamic> results = data['results'];

//Iterating over results list and converting to MovieModel
   results.forEach((element) {
     
//adding MovieModel object to movies list
movies.add(MovieModel.fromJson(element));
   });
 });
}

Displaying data

Now, data values can be accessed from the MovieModel object using its properties.

For example, movies[index]["poster_path"] can be accessed as movies[index].poster_path, and so on.

Previous code to render items in list can be updated to Text(movies[index].title).

Old way to retrieve title: movies[index]["title"]

class _MoviesListingState extends State<MoviesListing> {
  
...
    @override
  Widget build(BuildContext context) {
    //Fetching movies as usual
    fetchMovies();

    return Scaffold(
      body: ListView.builder(
        itemCount: movies == null ? 0 : movies.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: const EdgeInsets.all(8.0),
           //NEW CODE: New way to display title
           //Title is being accessed as below rather `movies[index]["title"]`
            child: Text(movies[index].title),
          );
        },
      ),
    );
  }
}

At this point, the response from API is rendered as a text blob on the main screen.

Get hands-on with 1200+ tech skills courses.