Files
AAU-Store/lib/controllers/notification/notification_controller.dart

93 lines
2.6 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:laundry_seller/models/notification/store_notification.dart';
import 'package:laundry_seller/services/notification/notification_service_provider.dart';
class NotificationState {
final List<StoreNotification> notifications;
final int unreadCount;
final bool isLoading;
NotificationState({
this.notifications = const [],
this.unreadCount = 0,
this.isLoading = false,
});
NotificationState copyWith({
List<StoreNotification>? notifications,
int? unreadCount,
bool? isLoading,
}) {
return NotificationState(
notifications: notifications ?? this.notifications,
unreadCount: unreadCount ?? this.unreadCount,
isLoading: isLoading ?? this.isLoading,
);
}
}
class NotificationController extends StateNotifier<NotificationState> {
final Ref ref;
NotificationController(this.ref) : super(NotificationState()) {
fetchData();
}
Future<void> fetchData() async {
state = state.copyWith(isLoading: true);
try {
final resList =
await ref.read(notificationServiceProvider).getNotifications();
final resCount =
await ref.read(notificationServiceProvider).getUnreadCount();
int count = 0;
List<StoreNotification> list = [];
if (resList.data != null && resList.data is Map && resList.data['data'] != null) {
final List<dynamic> data = resList.data['data'];
list = data
.map((e) => StoreNotification.fromMap(Map<String, dynamic>.from(e)))
.toList();
}
if (resCount.data != null && resCount.data is Map && resCount.data['data'] != null) {
count = resCount.data['data']['count'] ?? 0;
}
state = state.copyWith(
notifications: list,
unreadCount: count,
isLoading: false,
);
} catch (e) {
debugPrint(e.toString());
state = state.copyWith(isLoading: false);
}
}
Future<void> markRead(int id) async {
try {
await ref.read(notificationServiceProvider).markRead(id);
fetchData(); // Refresh list and count
} catch (e) {
debugPrint(e.toString());
}
}
Future<void> markAllRead() async {
try {
await ref.read(notificationServiceProvider).markAllRead();
fetchData(); // Refresh list and count
} catch (e) {
debugPrint(e.toString());
}
}
}
final notificationControllerProvider =
StateNotifierProvider<NotificationController, NotificationState>((ref) {
return NotificationController(ref);
});