我想保存所有将从 Firebase 发送的推送通知并在应用程序中显示所有通知。
我试过了,但所有通知都没有保存..
这是我的通知模型
class NotificationModel extends Equatable { final String title; final String body;
const NotificationModel({
required this.title,
required this.body, });
NotificationModel copyWith({
String? title,
String? body, }) {
return NotificationModel(
title: title ?? this.title,
body: body ?? this.body,
); }
Map<String, dynamic> toMap() {
return <String, dynamic>{
'title': title,
'body': body,
}; }
factory NotificationModel.fromMap(Map<String, dynamic> map) {
return NotificationModel(
title: map['title'] as String,
body: map['body'] as String,
); }}
我声明一个通知列表 notificationList = [];
保存标题和正文
void saveNotification(String title, String body) async {
NotificationModel notification =
NotificationModel(title: title, body: body);
String jsonData = jsonEncode(notification);
sharedPreferences.setString('notification', jsonData);
print('SavedNotification: $jsonData'); }
从这个方法获取数据..
void initializeData() async {
sharedPreferences = await SharedPreferences.getInstance();
//final result = sharedPreferences.getString('notification');
final result =
await json.decode(sharedPreferences.getString('notification')!);
print('type: ${result.runtimeType}');
NotificationModel model = NotificationModel.fromJson(result);
if (result.isNotEmpty) {
notificationList
.add(NotificationModel(title: title ?? '', body: description ?? ''));
title = model.title;
description = model.body;
}
}
FirebaseMessaging.onMessage.listen(
(event) {
RemoteNotification? notification = event.notification;
AndroidNotification? android = event.notification!.android;
if (notification != null && android != null) {
_localNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
channelDescription: channel.description,
icon: '@mipmap/ic_launcher'),
),
);
}
saveNotification(notification.title!, notification.body!);
print('SaveData success');
// print('Saved Data: ${sharedPreferences.getString('title')}');
},
每次我得到最新的头衔和身体...
您正在用“通知”共享首选项键中的最新通知数据替换最后一个通知 JSON 数据。您应该将 list of JSON <NotificationModel> JSON strings
存储在 notification
共享首选项中。
为此更新您的 saveNotification()
方法。你只存储一个NotificationModel
而不是这个在List< NotificationModel>中添加那个模型然后存储这个更新的通知列表JSON.
注:
在
saveNotification()
中,您还需要获取先前存储的第一个旧通知列表。
来自共享偏好的数据并添加新通知并保存 更新列表。