尝试使用共享首选项保存推送通知并获取该标题和 body

trying to save push notification using shared preference and get that title and body

我正在尝试使用 shared_preference 保存推送通知标题和 body,并尝试在我的卡片视图或 listtile 中获取保存的数据,这意味着我想在我的应用程序中显示通知列表我使用共享首选项在本地保存:

    static List<String?> detail = [];
    
    FirebaseMessaging.onMessage.listen((message) async{
      if(message.notification!=null){
        // print(message.notification!.body);
        // print(message.notification!.title);
        final title = message.notification?.title;
        final body = message.notification?.body;
        SharedPreferences prefs = await SharedPreferences.getInstance();
        final String notificationData = json.encode({"title":title,"body":body});
        detail.add(notificationData);
        final data = prefs.setString('notificationData', detail.toString());
        print(data);
        print(detail);
      }
      LocalNotificationService.display(message);
    });


    FirebaseMessaging.onMessageOpenedApp.listen((message) async{
      final routeFromMessage = message.data["routeKey"];
      // RemoteNotification? notification = message.notification;
      final title = message.notification?.title;
      final body = message.notification?.body;
      SharedPreferences prefs = await SharedPreferences.getInstance();
      final String notificationData = json.encode({"title":title,"body":body});
      detail.add(notificationData);
      final data = prefs.setString('notificationData', detail.toString());
      print(data);
      print(detail);
      Navigator.of(context).pushNamed(routeFromMessage);
    });

正在保存数据,但我的旧通知正在被新的通知替换,并且只显示新的通知

我正在尝试像这样获取我保存的数据:

  Future<String?> getNotification() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.getString("notificationData");
  }

我想在卡片视图或列表视图中获取我的所有通知列表:

    Card(
      child: FutureBuilder(
        future: getNotification(),
        builder: (context, notificationSnapshot) {
          if (notificationSnapshot.connectionState == ConnectionState.none &&
              notificationSnapshot.hasData) {
            return const Text("No Notification to Show");
          }
          return ListTile(
            title: Text("$detail"),
          );
        },
      ),
    )

步骤 1

先获取detail列表值

步骤 2

然后将 notificationData 添加到 detail 列表中

因此您的列表值无法替换为较新的值。 希望对你有帮助