72 lines
2.4 KiB
Dart
72 lines
2.4 KiB
Dart
import 'package:cheminova/controller/product_service.dart';
|
|
import 'package:cheminova/models/product_model1.dart';
|
|
import 'package:get/get.dart';
|
|
|
|
|
|
class ProductController extends GetxController {
|
|
// Instantiate the product service
|
|
final ProductService productService = ProductService();
|
|
var products = <Product>[].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();
|
|
// Fetch categories when the controller initializes
|
|
getCategory();
|
|
// Fetch products when the controller initializes
|
|
getUser();
|
|
}
|
|
// Method to fetch products based on the selected category and current page
|
|
Future<void> getUser() async {
|
|
if (isLoading) return; // Prevent duplicate calls if already loading
|
|
isLoading = true;
|
|
try {
|
|
final category = selectedCategory.value; // Get the selected category
|
|
final fetchedProducts = await productService.getProduct(
|
|
_currentPage,
|
|
category: category,
|
|
);
|
|
|
|
if (fetchedProducts != null) {
|
|
// If products were fetched, add them to the observable list
|
|
products.addAll(fetchedProducts);
|
|
print("fetchedProducts ,$fetchedProducts");
|
|
}
|
|
} catch (e) {
|
|
print("Error fetching products: $e");
|
|
} finally {
|
|
isLoading = false;
|
|
update();
|
|
}
|
|
}
|
|
// Method to fetch categories from the product service
|
|
Future<void> getCategory() async {
|
|
try {
|
|
final fetchedCategories = await productService.getCategory();
|
|
if (fetchedCategories != null) {
|
|
// If categories were fetched, map them to the observable list
|
|
categories.assignAll(fetchedCategories.map((category) => category['categoryName'] as String));
|
|
categories.insert(0, 'All'); // Add "All" option as the first category
|
|
}
|
|
} catch (e) {
|
|
print("Error fetching categories: $e");
|
|
}
|
|
}
|
|
// Method to set the selected category and fetch products
|
|
void setCategory(String category) {
|
|
selectedCategory.value = category == 'All' ? null : category;
|
|
_currentPage = 1;
|
|
products.clear(); // Clear the existing products
|
|
getUser(); // Fetch products based on the new category
|
|
}
|
|
// Method to load more products when reaching the end of the list
|
|
void loadMoreProducts() {
|
|
_currentPage++;
|
|
getUser(); // Fetch products for the next page
|
|
}
|
|
}
|