I want to display push notifications in a separate page in my app

I only want to display all the unread notifications in the messages page. Whenever I tap on a push notification I want to see the new notification along with other unread notifications in the page in all three states (foreground, background, terminated). It works fine for the foreground state. But when I tap on a push notification it in the background or terminated state, it displays all the received push notifications even though I already have read them.

I am storing a push notification in the shared preferences, whenever it receives. When I go to the messages page, the notifications get retrieved from the shared preferences and displays the unread notifications by checking the key ‘read’. A notification is marked as read by tapping on it and this makes the ‘read’ key true and get removed from the notifications list.

This is code of the messages page.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class NotificationMessage extends StatefulWidget {
  const NotificationMessage({super.key});

  @override
  State<NotificationMessage> createState() => _NotificationMessageState();
}

class _NotificationMessageState extends State<NotificationMessage> {
  List<Map<String, dynamic>> notifications = [];
  String role = "";

  @override
  void initState() {
    super.initState();
    checkRole();
    _loadNotifications();
  }

  Future<void> checkRole() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
    role = prefs.getString('role') ?? 'customer';
    if (!isLoggedIn) {
      Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
    }
  }

  Future<void> _loadNotifications() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.reload().then((value) {
      List<String> storedNotifications = prefs.getStringList('notifications') ?? [];
      print("Stored Notifications - ${storedNotifications.length}");
      print(storedNotifications);
      // Decode stored notifications and add them to the list
      setState(() {
        notifications = storedNotifications.map((notification) {
          return jsonDecode(notification) as Map<String, dynamic>;
        }).toList();
      });
    });
  }

  Future<void> _saveNotifications() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final List<String> jsonList = notifications.map((e) => jsonEncode(e)).toList();
    prefs.setStringList('notifications', jsonList);
  }

  Future<void> _removeReadNotifications(List<Map<String, dynamic>> notifications) async {
    notifications.removeWhere((element) => element['read'] == true);
    await _saveNotifications();
  }

  void _markAsRead(int index) async {
    setState(() {
      notifications[index]['read'] = true;
    });
    await _saveNotifications();
    print(notifications[index]);
    await _removeReadNotifications(notifications);
    print('!!!');
    print(notifications);
  }

  String _formatTimestamp(DateTime? timestamp) {
    if (timestamp == null) {
      return "Unknown Time";
    }

    final now = DateTime.now();
    final difference = now.difference(timestamp);

    if (difference.inMinutes < 1) {
      return "Just now";
    } else if (difference.inHours < 1) {
      return "${difference.inMinutes} minutes ago";
    } else if (difference.inDays < 1) {
      return "${difference.inHours} hours ago";
    } else {
      return "${difference.inDays} days ago";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text('Notifications'),
        backgroundColor: Colors.white38,
        elevation: 0.0,
      ),
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/background2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: ListView.builder(
            padding: const EdgeInsets.all(16.0),
            itemCount: notifications.length,
            itemBuilder: (context, index) {
              final notification = notifications[index];
              print(notifications[index]['timestamp']);
              return Padding(
                padding: const EdgeInsets.only(bottom: 16.0),
                child: GestureDetector(
                  onTap: () {
                    _markAsRead(index);
                  },
                  child: AnimatedOpacity(
                    opacity: notification['read'] ? 0.6 : 1.0,
                    duration: Duration(milliseconds: 300),
                    child: Container(
                      padding: const EdgeInsets.all(16.0),
                      decoration: BoxDecoration(
                        color: notification['read'] ? Colors.grey[200] : Colors.white,
                        borderRadius: BorderRadius.circular(10.0),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black26,
                            blurRadius: 5.0,
                            offset: Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            notification['title'],
                            style: TextStyle(
                              fontSize: 18.0,
                              fontWeight: FontWeight.bold,
                              color: Colors.black,
                            ),
                          ),
                          SizedBox(height: 8.0),
                          Text(
                            notification['body'],
                            style: TextStyle(
                              fontSize: 16.0,
                              color: Colors.black87,
                            ),
                          ),
                          SizedBox(height: 8.0),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Text(
                                _formatTimestamp(DateTime.parse(notification['timestamp'])),
                                style: TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
          BottomNavigationBarItem(icon: Icon(Icons.shopping_cart), label: "Activities"),
          BottomNavigationBarItem(icon: Icon(Icons.notifications), label: "Notifications"),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: "Profile"),
        ],
        currentIndex: 2,
        onTap: (int n) {
          if (n == 0) {
            if (role == 'customer') {
              _removeReadNotifications(notifications);
              Navigator.pushNamedAndRemoveUntil(context, '/customer_home', (route) => false);
            } else {
              Navigator.pushNamedAndRemoveUntil(context, '/pharmacy_home', (route) => false);
            }
          }
          if (n == 1) {
            if (role == 'customer') {
              Navigator.pushNamedAndRemoveUntil(context, '/activities', (route) => false);
            } else {
              Navigator.pushNamedAndRemoveUntil(context, '/orders', (route) => false);
            }
          }
          if (n == 3) {
            if (role == 'customer') {
              Navigator.pushNamedAndRemoveUntil(context, '/profile', (route) => false);
            } else {
              Navigator.pushNamedAndRemoveUntil(context, '/pharmacy_profile', (route) => false);
            }
          }
        },
        selectedItemColor: const Color(0xFF0CAC8F),
      ),
    );
  }
}

This is the code for push notification services.

import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:http/http.dart' as http;
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:medifinder/main.dart';

class PushNotifications {
  // Create an instance of firebase messaging
  static final _firebaseMessaging = FirebaseMessaging.instance;
  static final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  // Function to initialize notifications
  static Future initNotifications() async {
    // Request permission from user
    await _firebaseMessaging.requestPermission(
        alert: true,
        announcement: true,
        badge: true,
        carPlay: false,
        criticalAlert: true,
        provisional: false,
        sound: true
    );
    final fCMToken = await _firebaseMessaging.getToken();
    print("device token: $fCMToken");

    // Check if the app was launched by tapping on a notification
    FirebaseMessaging.instance.getInitialMessage().then((message) {
      if (message != null) {
        // Navigate to the message page with the notification data
        navigatorKey.currentState!.pushNamed('/message', arguments: message);
      }
    });

    // Handle background message taps
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      navigatorKey.currentState!.pushNamed('/message', arguments: message);
    });

    // Initialize local notifications
    await PushNotifications().localNotiInit();
  }

  Future<String?> getDeviceToken() async {
    // Fetch the FCM token for this device
    final fCMToken = await _firebaseMessaging.getToken();
    print("device token: $fCMToken");
    return fCMToken;
  }

  Future addDeviceToken(String userRole, String userID) async {
    // Fetch the FCM token for this device
    final fCMToken = await _firebaseMessaging.getToken();
    print("device token: $fCMToken");

    late DocumentSnapshot<Map<String, dynamic>> userDoc;
    if (userRole == 'customer') {
      userDoc =
      await FirebaseFirestore.instance.collection('Users').doc(userID).get();

      // _firebaseMessaging.onTokenRefresh.listen((event) async {
      //   DocumentReference userDoc = FirebaseFirestore.instance.collection('Users').doc(userID);
      //   await userDoc.update({'FCMTokens': FieldValue.arrayUnion([fCMToken])});
      // });

    } else if (userRole == 'pharmacy') {
      userDoc = await FirebaseFirestore.instance.collection('Pharmacies')
          .doc(userID)
          .get();
    }

    if (userDoc.exists) {
      Map<String, dynamic>? userData = userDoc.data();
      if (userData != null) {
        List<String> tokens = List<String>.from(userData['FCMTokens']);
        if (!tokens.contains(fCMToken)) {
          tokens.add(fCMToken!);
          await userDoc.reference.update({'FCMTokens': tokens,});
        }
      }
      else {
        throw Exception('Error fetching user data.');
      }
    } else {
      throw Exception('Error fetching user.');
    }

    //await _firebaseMessaging.deleteToken();
  }

  // Initialize local notifications
  Future localNotiInit() async {
    // Initialize the plugin, app_icon needs to be added as a drawable resource
    const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings(
        '@mipmap/ic_launcher');
    final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
    );

    // Request notification permission for android 13 or above
    _flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()!
        .requestNotificationsPermission();

    _flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onDidReceiveNotificationResponse: onNotificationTap,
        onDidReceiveBackgroundNotificationResponse: onNotificationTap);
  }

  // On tap notification in foreground
  static void onNotificationTap(NotificationResponse notificationResponse) {
    navigatorKey.currentState!.pushNamed(
        '/message', arguments: notificationResponse);
  }

  // Show a simple notification
  static Future showSimpleNotification(
      {required String title, required String body, required String payload}) async {
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('your channel id', 'your channel name',
        channelDescription: 'your channel description',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker'
    );
    const NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails);
    await _flutterLocalNotificationsPlugin.show(
        0, title, body, notificationDetails, payload: payload);
  }
}

This is the code for initializations and storing push notifications.

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void _saveNotification(RemoteMessage message) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  List<String> notifications = prefs.getStringList('notifications') ?? [];
  print("Notifications length in save notification before ${notifications.length}");
  // Notification map
  Map<String, dynamic> notification = {
    'title': message.notification?.title ?? 'No Title',
    'body': message.notification?.body ?? 'No Body',
    'data': message.data,
    'timestamp': DateTime.now().toString(),
    'read': false
  };

  notifications.insert(0, jsonEncode(notification));
  print("Notifications length in save notification after ${notifications.length}");
  prefs.setStringList('notifications', notifications);
}

// Function to listen to background changes
Future _firebaseBackgroundMessage(RemoteMessage message) async {
  if (message.notification != null) {
    _saveNotification(message);
    print('Some notification received in background...');
  }
}

await PushNotifications.initNotifications();

  // Initialize local notifications
  await PushNotifications().localNotiInit();

  // Listen to background notifications
  FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessage);

  // On background notification tapped
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    if (message.notification != null) {
      print('Background notification tapped');
      navigatorKey.currentState!.pushNamed('/message', arguments: message);
    }
  });

  // To handle foreground notifications
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    String payloadData = jsonEncode(message.data);
    print('Got a message in foreground');
    if (message.notification != null) {
      PushNotifications.showSimpleNotification(
          title: message.notification!.title!,
          body: message.notification!.body!,
          payload: payloadData);
    }
    _saveNotification(message);
  });

  // For handling in terminated state
  final RemoteMessage? message =
      await FirebaseMessaging.instance.getInitialMessage();
  if (message != null) {
    _saveNotification(message);
    print('Launched in terminated state');
    Future.delayed(Duration(seconds: 1), () {
      navigatorKey.currentState!.pushNamed('/message', arguments: message);
    });
  }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật