Creating the app and connecting to the API with the HTTP library

Let's create a new Flutter app. We will call it Movies:

  1. The first thing to do is to open the pubspec.yaml file and add a dependency to the HTTP library, which we'll use to make HTTP requests. Please check the latest available version at https://pub.dev/packages/http.
    Add the http library under the flutter dependency, as follows: 
dependencies:
flutter:
sdk: flutter
http: ^0.12.0+4
  1. Then, let's create a new file, called http_helper.dart, that we'll use to create the settings and methods that we'll use to connect to the web service. In the new file, let's import the HTTP library:
import 'package:http/http.dart' as http;

With the as http command, we are giving the library a name and therefore, we'll be using all functions and classes of the HTTP library through the http name.

  1. Then, let's create a new class, which we'll call HttpHelper:
class HttpHelper {}
  1. The next step is creating the address url to connect to the service. This will require a few strings, which we'll concatenate as needed to retrieve data from the service. Add the following declarations at the top of the HttpHelper class:
 final String urlKey = 'api_key=YOUR API KEY HERE';
final String urlBase = 'https://api.themoviedb.org/3/movie';
final String urlUpcoming = '/upcoming?';
final String urlLanguage = '&language=en-US';

To make it easier to retrieve the values of these strings, all of them begin with a url prefix. The first string, urlKey, contains the value, api_key =, and the API key you've obtained from the Movie Database service. The urlBase string is the beginning of every address we'll be using. urlUpcoming is the part of the URL that's specific for the upcoming movies. Finally, urlLanguage contains an optional parameter that allows you to specify which language you want to use for the results of your queries.

  1. We are now ready to write the first method of this class, which we'll use to retrieve a list of 20 upcoming movies:
Future<String> getUpcoming() async { }

You may notice an unfamiliar syntax here. The getUpcoming() function returns a future and is signed as async. These two elements are both related to asynchronous programming.

In Chapter 3, My Time – Listening to a Stream of Data, you have already used asynchronous programming with streams. In this chapter, you'll see how to use Futures.

Generally speaking, when you run your code, for example, in a method, each line executes from the first to the last, in order. If there are 10 lines of code in your function, line 5 executes only after line 4 has finished executing.

On the other hand, we generally take for granted that our devices can do more than one thing at the same time. When you are listening to music on your device, you also expect to be able to browse your playlist or adjust the volume. You would be very disappointed if you had to wait for the song to finish before being able to adjust the volume! 

The thing is, by default, every single action is executed is a single thread, generally called the main thread, or the UI thread.

You should avoid an unresponsive UI at all costs: after a few seconds, both Android and iOS will ask the user if they want to kill your app.

What we can do to solve this issue in Flutter is create different isolates, or lines of execution, when we have long-running tasks in our app so that, for example, our network tasks run at the same time (or concurrently) as our main thread. 

Concurrency is what happens when two or more tasks can start, run, and complete in overlapping time periods.

In other words, asynchronous operations let your program complete work while waiting for another operation to finish. Here are some common asynchronous scenarios:

  • Retrieving data from the web
  • Reading and writing data to a file
  • Reading and writing to a local database

To perform asynchronous operations in Flutter, you can use the Future class and the async, await, and then keywords.

A Future is used to represent a potential value, or error, that will be available at some time in the future. Basically, when a function returns a Future, it means that it takes a while for its result to be ready, and the result will be available in the future. The Future itself is returned immediately and its underlying object is returned at some time in the future.

Writing Future<String> means that the function will immediately return a Future without interrupting the code, and then, when it completes retrieving all of the data, it will return String.

In the getUpcoming() method, we are adding the async keyword. In Dart and Flutter, you must add async when you use an await keyword in the body of the function. Any method returning a Future is asynchronous anyway, whether or not you mark it with async.

Let's retrieve some data from the web service:

  1. In the getUpcoming method, let's add a string to create the URL that we'll use during the connection:
final String upcoming = urlBase + urlUpcoming + urlKey + urlLanguage;
  1. Next, let's use the HTTP library to create a connection to the URL we've built:
http.Response result = await http.get(upcoming);

The get method of the http class returns a Future that contains Response. The http.Response class contains the data that has been received from a successful HTTP call.

The await keyword, which only works in functions marked as async, waits for a Future to complete. It won't go to the next line of its thread until it completes this line, behaving a lot like synchronous code, but remember, this happens on a secondary line of execution, so it won't stop the UI thread.

  1. Now, how do we read the response? Let's write the following code:
if (result.statusCode == HttpStatus.ok) {
String responseBody = result.body;
return responseBody;
}
else {
return null;
}
  1. The HttpStatus class requires the dart:io library. At the top of the http_helper.dart file, add the required import:
import 'dart:io';

Response has statusCode and body properties. The status code may express a successful response, which is a code 200 of HttpStatus.ok or an error. You may be familiar with error 404; in Dart, you would just express it with HttpStatus.notFound.

In the preceding code, if the response has a valid status code, we read the body of the response, which is a string containing all of the data that was retrieved by the http.get method, and we return it to the caller.

To sum it up, we now have an asynchronous function that makes an HTTP request and returns a Future containing a string. Now we need to call this function from the main method and show the result to the user. Let's do that next.

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

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