Commit 8032ad3b authored by Ilham Maulana's avatar Ilham Maulana 💻

feat: filter book by category and refactoring

parent 6c33449f
...@@ -9,12 +9,20 @@ class BookProvider with ChangeNotifier { ...@@ -9,12 +9,20 @@ class BookProvider with ChangeNotifier {
List<dynamic>? categories; List<dynamic>? categories;
Category? category; Category? category;
BookProvider({this.books}); String? searchKeyword;
String? filterByCategory;
Future<void> getBooks() async { Future<void> getBooks() async {
try { try {
String url = '$baseUrl/books';
if (filterByCategory != null) {
url += '?category__name=$filterByCategory';
} else if (searchKeyword != null) {
url += "?search=$searchKeyword";
}
final response = await http.get( final response = await http.get(
Uri.parse('$baseUrl/books'), Uri.parse(url),
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
); );
...@@ -32,25 +40,14 @@ class BookProvider with ChangeNotifier { ...@@ -32,25 +40,14 @@ class BookProvider with ChangeNotifier {
} }
} }
Future<void> searchBook(String? keyword) async { void filterBookByCategory(String? name) {
try { filterByCategory = name;
final response = await http.get( notifyListeners();
Uri.parse('$baseUrl/books?search=$keyword'),
headers: {'Content-Type': 'application/json'},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
books = data["results"];
} else {
final code = response.statusCode;
debugPrint("Error: Fetch books failed, $code");
} }
void setSearchKeyword(String? keyword) {
searchKeyword = keyword;
notifyListeners(); notifyListeners();
} catch (error) {
debugPrint("Error: Fetch books failed, $error");
}
} }
Future<void> getCategories() async { Future<void> getCategories() async {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment