pd-android-app/lib/controller/product_service.dart
saritabirare ff065bdc16 1) annaucement api integration done
2)Billto and shipTo api integration
2024-10-22 10:36:49 +05:30

69 lines
2.2 KiB
Dart

import 'package:cheminova/utils/api_urls.dart';
import '../models/product_model1.dart';
import '../utils/common_api_service.dart';
import '../utils/show_snackbar.dart';
class ProductService {
// Method to fetch products based on the page number and optional category
Future<List<Product>?> getProduct(int page, {String? category}) async {
try {
String url;
// Determine the URL based on the presence of a category filter
if (category != null && category.isNotEmpty) {
url = "${ApiUrls.getallProductUrl}?page=$page&category=$category";
}
else {
url = "${ApiUrls.getallProductUrl}?page=$page"; // URL without category filter
}
// Make the API call using the common API service
final response = await commonApiService<List<Product>>(
method: "GET",
url: url,
fromJson: (json) {
if (json['products'] != null) {
// If the 'products' key exists, map it to a list of Product objects
final List<Product> products = (json['products'] as List)
.map((productJson) => Product.fromJson(productJson as Map<String, dynamic>))
.toList();
return products;
} else {
return [];
}
},
);
return response;
} catch (e) {
// showSnackbar(e.toString());
return null;
}
}
// Method to fetch product categories
Future<List<Map<String, dynamic>>?> getCategory() async {
try {
// Make the API call to fetch categories
final response = await commonApiService<List<Map<String, dynamic>>>(
method: "GET",
url: ApiUrls.getCategoryUrl,
fromJson: (json) {
if (json['categories'] != null) {
final List<Map<String, dynamic>> category = (json['categories'] as List)
.map((productJson) => productJson as Map<String, dynamic>)
.toList();
return category; // Return the list of categories
} else {
return []; // Return an empty list if no categories are found
}
},
);
return response;
} catch (e) {
showSnackbar(e.toString());
print("Error: $e");
}
return null;
}
}