pd-android-app/lib/controller/product_controller.dart
saritabirare 43413ac168 1)getProduct api Integration
2)getCategory wise product api integration
3)Category wise product filter added
2024-08-30 11:26:38 +05:30

65 lines
1.7 KiB
Dart

import 'package:cheminova/controller/product_service.dart';
import 'package:get/get.dart';
class ProductController extends GetxController {
final ProductService productService = ProductService();
var products = <Map<String, dynamic>>[].obs;
var categories = <String>[].obs; // Holds the list of categories
var selectedCategory = Rxn<String>(); // Holds the selected category
int _currentPage = 1;
bool isLoading = false;
@override
void onInit() {
super.onInit();
getCategory();
getUser();
}
Future<void> getUser() async {
if (isLoading) return;
isLoading = true;
try {
final category = selectedCategory.value; // Get the selected category
final fetchedProducts = await productService.getProduct(
_currentPage,
category: category,
);
if (fetchedProducts != null) {
products.addAll(fetchedProducts as Iterable<Map<String, dynamic>>);
}
} catch (e) {
print("Error fetching products: $e");
} finally {
isLoading = false;
update();
}
}
Future<void> getCategory() async {
try {
final fetchedCategories = await productService.getCategory();
if (fetchedCategories != null) {
categories.assignAll(fetchedCategories.map((category) => category['categoryName'] as String));
categories.insert(0, 'All'); // Add "All" option
}
} catch (e) {
print("Error fetching categories: $e");
}
}
void setCategory(String category) {
selectedCategory.value = category == 'All' ? null : category;
_currentPage = 1;
products.clear();
getUser();
}
void loadMoreProducts() {
_currentPage++;
getUser();
}
}