Parsing JSON data and transforming it into model objects

We are now ready to show the data that was retrieved from the web service in the UI:

  1. Open the main.dart file, delete the default code of the app, and create a basic empty app like this:
import 'package:flutter/material.dart';
void main() => runApp(MyMovies());
class MyMovies extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Movies',
theme: ThemeData(
primarySwatch: Colors.deepOrange,
),
home: Home(),
);
}
}

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MovieList();
}
}
  1. There's nothing new in this code. Just notice that we chose ThemeData, with Colors.deepOrange primarySwatch, and in Home StatelessWidget, we are calling the MovieList class, which we haven't created yet. Let's immediately fix this by adding a new file in our lib folder called movie_list.dart and adding a MovieList stateful widget:
import 'package:flutter/material.dart';

class MovieList extends StatefulWidget {
@override
_MovieListState createState() => _MovieListState();
}

class _MovieListState extends State<MovieList> {
@override
Widget build(BuildContext context) {
return Container();
}
}
  1. Let's import this new file in the main.dart file to fix the error we are receiving right now:
import 'movie_list.dart';

  1. Now, we need to show the data retrieved by the getUpcoming() async method in the HttpHelper class. To do that, first, let's import the http_helper.dart file at the top of the movie_list.dart file:
import 'http_helper.dart';
  1. In the _MovieListState class, let's create String that will contain the data that we need to show an HttpHelper called helper:
String result;
HttpHelper helper;
  1. Let's override the initState method and create an HttpHelper instance:
@override
void initState() {
helper = HttpHelper();
super.initState();
}
  1. Then, in the build method, we'll call the getUpcoming asynchronous method, and when the results are returned (this is the then method), we call the setState method to update the result string with the value that was returned:
 @override
Widget build(BuildContext context) {
helper.getUpcoming().then(
(value) {
setState(() {
result = value;
});
}
);
return Scaffold(
appBar: AppBar(title: Text('Movies'),),
body: Container(
child: Text(result)
));
}
  1. Next, we'll return Scaffold that, in its body, shows Container with a Text child, containing the result string.

 

  1. If you try the app right now, the end result should look similar to this:

Here, you have some text that takes up all of the available space on the screen and contains all of the JSON code retrieved from the Movies API. This is probably not the most user-friendly way to show data to your users, but we'll fix that next!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.50