64 lines
2.2 KiB
Dart
64 lines
2.2 KiB
Dart
import 'package:get/get.dart';
|
|
import '../models/announcement_response.dart';
|
|
import '../services/api_service.dart';
|
|
import '../utils/api_urls.dart';
|
|
|
|
class AnnouncementController extends GetxController {
|
|
final ApiService _apiClient = ApiService();
|
|
RxList<Announcements> announcementsList = <Announcements>[].obs;
|
|
RxBool isLoading = false.obs;
|
|
RxBool hasMoreData = true.obs; // To check if there are more pages to load
|
|
RxInt currentPage = 1.obs; // To track the current page
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
getAnnouncements(); // Fetch announcements when the controller initializes
|
|
}
|
|
|
|
Future<void> getAnnouncements({int page = 1, int rowsPerPage = 5}) async {
|
|
if (!hasMoreData.value) return; // Return if no more data is available
|
|
|
|
isLoading.value = true; // Set loading to true while fetching
|
|
try {
|
|
final response = await _apiClient.get(
|
|
"${ApiUrls.announcementUrl}?page=$page&rowsPerPage=$rowsPerPage",
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = response.data['announcements'];
|
|
AnnouncementResponse res=AnnouncementResponse.fromJson(response.data);
|
|
|
|
// If the fetched data length is less than rowsPerPage, it means no more data
|
|
if (data.length < rowsPerPage) {
|
|
hasMoreData.value = false;
|
|
}
|
|
|
|
final newAnnouncements = data.map((item) => AnnouncementResponse.fromJson(item)).toList();
|
|
|
|
// If it's the first page, replace the list; else append to the existing list
|
|
if (page == 1) {
|
|
announcementsList.value =res.announcements??[];
|
|
} else {
|
|
announcementsList.addAll(res.announcements??[]);
|
|
}
|
|
|
|
// Update the current page
|
|
currentPage.value = page;
|
|
} else {
|
|
Get.snackbar('Error', 'Failed to fetch announcements: ${response.statusCode} - ${response.statusMessage}');
|
|
}
|
|
} catch (e) {
|
|
Get.snackbar('Error', 'Failed to fetch announcements: $e');
|
|
} finally {
|
|
isLoading.value = false; // Ensure loading is set to false in the finally block
|
|
}
|
|
}
|
|
|
|
void loadMoreAnnouncements() {
|
|
if (hasMoreData.value) {
|
|
getAnnouncements(page: currentPage.value + 1); // Load the next page
|
|
}
|
|
}
|
|
}
|