93 lines
2.7 KiB
Dart
93 lines
2.7 KiB
Dart
import 'package:firebase_messaging/firebase_messaging.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
|
|
|
|
|
|
|
class NotificationController extends GetxController {
|
|
var notifications = <Map<String, String>>[].obs; // List of notifications
|
|
late FlutterLocalNotificationsPlugin localNotifications;
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
initNotifications();
|
|
}
|
|
|
|
void initNotifications() async {
|
|
localNotifications = FlutterLocalNotificationsPlugin();
|
|
|
|
const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
|
|
const iosSettings = DarwinInitializationSettings(); // Updated for iOS
|
|
await localNotifications.initialize(
|
|
const InitializationSettings(android: androidSettings, iOS: iosSettings),
|
|
);
|
|
|
|
// Listen for FCM foreground messages
|
|
FirebaseMessaging.onMessage.listen((message) {
|
|
showNotification(message);
|
|
notifications.insert(0, {
|
|
'title': message.notification?.title ?? '',
|
|
'body': message.notification?.body ?? '',
|
|
});
|
|
update();
|
|
});
|
|
}
|
|
|
|
void showNotification(RemoteMessage message) async {
|
|
const androidDetails = AndroidNotificationDetails(
|
|
'channelId', 'channelName',
|
|
importance: Importance.max,
|
|
priority: Priority.high,
|
|
);
|
|
|
|
const iosDetails = DarwinNotificationDetails(); // Updated for iOS
|
|
const generalNotificationDetails =
|
|
NotificationDetails(android: androidDetails, iOS: iosDetails);
|
|
|
|
await localNotifications.show(
|
|
0,
|
|
message.notification?.title ?? '',
|
|
message.notification?.body ?? '',
|
|
generalNotificationDetails,
|
|
);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
class NotificationPage extends StatelessWidget {
|
|
final NotificationController controller = Get.put(NotificationController());
|
|
|
|
NotificationPage({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: const Text('Notifications'),
|
|
centerTitle: true,
|
|
),
|
|
body: Obx(() {
|
|
if (controller.notifications.isEmpty) {
|
|
return const Center(child: Text("No notifications yet"));
|
|
}
|
|
return ListView.builder(
|
|
itemCount: controller.notifications.length,
|
|
itemBuilder: (context, index) {
|
|
final notification = controller.notifications[index];
|
|
return ListTile(
|
|
leading: const Icon(Icons.notifications),
|
|
title: Text(notification['title'] ?? ''),
|
|
subtitle: Text(notification['body'] ?? ''),
|
|
);
|
|
},
|
|
);
|
|
}),
|
|
);
|
|
}
|
|
}
|