Adding the search feature

By leveraging the Movie Database web service search feature, we'll allow our users to search any movie by title. What we want to do is show a search icon button in the AppBar. When the user taps on the button they will be able to enter part of a movie title into a TextField, and when they press the search button on the keyboard, the app will call the web service to retrieve all movies that contain the user's input.

Let's add the logic that we'll use to implement the search feature and call the Movie Database web API with the title we want to search:

  1. In the http_helper.dart file, in the HttpHelper class, let's declare a final String, containing the beginning of the URL required to perform a movie search. Obviously each API has its own URL structure, but most public web services have thorough documentation that will help you to build the correct URLs:
final String urlSearchBase = 'https://api.themoviedb.org/3/search/movie?api_key=[YOUR API KEY HERE]&query=';
I generally recommend creating a settings structure in your files. For example, in this project, we set all of the URL constants at the beginning of the httpHelper class. It's usually not a good idea to build the URLs when you need to use them, as your code gets harder to debug.
  1. Next, let's create a new function, called findMovies, that will return a List of Movies, and will take a string containing the title or part of the title:
Future<List> findMovies(String title) async {
final String query = urlSearchBase + title ;
http.Response result = await http.get(query);
if (result.statusCode == HttpStatus.ok) {
final jsonResponse = json.decode(result.body);
final moviesMap = jsonResponse['results'];
List movies = moviesMap.map((i) =>
Movie.fromJson(i)).toList();
return movies;
}
else {
return null;
} }
  1. In the findMovies() function, we first create the query to pass to the web API, which is a concatenation of urlSearchBase and the title that was passed to the function.
  2. Then we call the http.get method, passing the query and getting back a Response object, which we call result.

If the status code of result is HttpStatus.ok, we decode and parse the body of the result and create and return a List of Movies based on the result. The process is very similar to the getUpcoming method, but here we are passing a query based on the user input.

  1. Next, we need to implement the search function in the UI. There are several ways we could achieve this, but what we'll do is leverage the AppBar widget, which can contain not only text but also icons, buttons, and several other widgets, including a TextField.
  2. Let's get back to the movie_list.dart file. We'll create two properties in the _MovieListState class: one for the visible icon (the search icon when the screen is loaded) and the second a generic widget that at the beginning will be a Text widget containing Movies:
Icon visibleIcon = Icon(Icons.search);
Widget searchBar= Text('Movies');
  1. Next, in the appBar of the Scaffold in the build() method, let's change the title to take the searchBar widget, and let's add an actions parameter. This takes an array of widgets that are displayed after the title. Usually, they are buttons representing common operations. This will only contain a single IconButton containing Icons.search:
  title: searchBar,
actions: <Widget>[
IconButton(
icon: visibleIcon,
onPressed: () {}
),]),
  1. For the onPressed function of IconButton, we'll call the setState method so that we can show the TextField and change the icon when the user presses the search button:
onPressed: () {
setState(() {
if (this.visibleIcon.icon == Icons.search) {
this.visibleIcon = Icon(Icons.cancel);
this.searchBar = TextField(
textInputAction: TextInputAction.search,
style: TextStyle(
color: Colors.white,
fontSize: 20.0, ),
); }
else {
setState(() {
this.visibleIcon = Icon(Icons.search);
this.searchBar= Text('Movies');
});}});},

A few notes about the preceding code: Icons.search and Icons.cancel are two graphics that should help to make it clear what actions can be expected in the app. You can find a full updated list of the available Flutter icons at https://api.flutter.dev/flutter/material/Icons-class.html.

The textInputAction property of TextField allows you to specify the main action of the soft keyboard. TextInputAction.search should show a magnifying glass on the keyboard, but the end result always depends on the operating system you're using.

If you try the app right now, you'll notice that the search button is visible at the top right of the screen, and if you tap on it, input text will appear on AppBar, allowing you to type some text.

Now, we only need to call the findMovies method from the HttpHelper class when the user presses the search button on the keyboard.

  1. In the _MovieListState class, let's write a method to do that: we can call it search. It will be asynchronous, as it will be calling an async function, and it takes the text that's been typed by the user:
Future search(text) async {
movies = await helper.findMovies(text);
setState(() {
moviesCount = movies.length;
movies = movies;
});
}

The purpose of the search method is to call the HttpHelper findMovies method, wait for its result, and then call the setState method to update the moviesCount and movies properties so that the UI will show the movies that were found.

  1. Finally, in the TextField in the AppBar, let's call the search() method when the user submits the query:
onSubmitted: (String text) {
search(text);
},
  1. And if you try the app now, you'll be able to search for any movie you want:

Well done, your app is now complete! And by the way, if you have a look at the titles on the screen, you'll notice that there's a The Matrix 4 movie there: this is how I discovered that there would be a fourth installment of that movie! 

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

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