Solution: Implementing a Search Feature
View the solution of implementing the search feature in the Star Wars project.
We hope you did well in the previous exercise! It’s time to compare your solution to ours.
Implementing the search function
To implement the search function, we use the search feature of SWAPI API.
Press + to interact
Future<List<SwapiObject>> search(Category category, String query) async {String url = 'https://swapi.dev/api/${category.name}/?search=$query';http.Response response = await http.get(Uri.parse(url));if (response.statusCode == 200) {Map<String, dynamic> jsonResponse =Map<String, dynamic>.from(json.decode(response.body));List<dynamic> results = jsonResponse['results'];return results.map((e) => SwapiObject.fromJson(e)).toList();} else {throw Exception('Failed to load search results');}}
Line 2: We provide the category and the query to the request URL using
category.name
andquery
in the parameter.Line 4: We send the
get()
request....