Exercise: Implementing a Search Feature
Test your Flutter BLoC skills by implementing the search feature in the Star Wars application.
We'll cover the following
Practicing on your own is the best way to learn and make concepts click in your head. In this lesson, you’ll practice the concepts you’ve learned by implementing a new feature to the Star Wars project: a search feature.
Problem statement
We want to add the search feature to the category screen to help the user find items easily.
To implement the search feature, you need to create a new SearchBloc
. The events of this BLoC are provided to you under lib/bloc/search/search_events.dart
. You only have one event, the Search
event, which should be emitted when the user starts typing to search inside a category.
The states of this BLoC are provided to you under lib/bloc/search/search_states.dart
. You have the following states:
SearchInitial
: This is the initial state of the BLoC.SearchLoading
: This is emitted when the search results are being fetched from the API.SearchLoaded
: This is emitted when the search results are successfully fetched from the API.SearchError
: This is emitted when a problem occurs while the results are being fetched.
To implement this feature, you need to complete the following steps:
In
lib/services/search_service.dart
, implement the search function. You can use SWAPI API's search feature to get the results to be shown.In
lib/bloc/search/search_bloc.dart
, implement_mapSearchToState
.In
lib/app.dart
, provide theSearchBloc
to theSearchScreen
.In
lib/screens/search_screen/search_screen.dart
, implement theonChanged()
function of theTextField
. ThisTextfield
is where the user will write the query to search.
Note that the state changes are listened to inside lib/screens/search_screen/widgets/search_results.dart
using BlocBuilder
.
Note: Upon application execution, you can visit the URL after “Your app can be found at:” to view the app.
Get hands-on with 1200+ tech skills courses.