抱歉,我是 flutter 的新手,目前在为我的应用实现通知时遇到了困难。
我正在使用 flutter_local_notification
插件,因为我听说它可用于提醒目的,以及将其用于离线应用程序。
我目前面临将我的 Note(模型)对象传递给我的 onSelectNotification
的问题功能
我的目标:为我的 Note 应用创建一个提醒图标,这样当通知被 flutter_local_notification 插件触发时。点击通知将允许我继续我的 EditNotePage
事件,上面会出现对应的Note对象参数(标题、描述)
如何修改onSelectNotification
这样我就可以将我的 Note 对象传递给它。
非常感谢所有帮助!
抱歉没有提供太多代码。
FlutterLocalNotificationsPlugin
flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid =
new AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
var initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
最佳答案
您可以对您的 Note
进行编码对象到 JSON 字符串并将其传递到方法中以设置您的提醒,如下所示:
说这是你的 Note
类(class):
import 'package:meta/meta.dart';
import 'dart:convert';
class Note {
final String title;
final String description;
Note({@required this.title, @required this.description});
//Add these methods below
factory Note.fromJsonString(String str) => Note._fromJson(jsonDecode(str));
String toJsonString() => jsonEncode(_toJson());
factory Note._fromJson(Map<String, dynamic> json) => Note(
title: json['title'],
description: json['description'],
);
Map<String, dynamic> _toJson() => {
'title': title,
'description': description,
};
}
现在,要设置通知,您可以从模型创建 JSON 字符串并将其作为 payload
传递。到 flutterLocalNotificationsPlugin
方法如下: Note newNote = Note(title : 'Hello', description : 'This is my first reminder');
String noteJsonString = newNote.toJsonString();
await flutterLocalNotificationsPlugin.show(
0, 'plain title', 'plain body', platformChannelSpecifics,
payload: noteJsonString);
接下来你会得到 payload
您的 onSelectNotification
中的字符串方法和使用fromJsonString
构造函数(它解码 json 字符串并创建一个 Note
对象)来获取 Note
目的: Future onSelectNotification(String payload) async {
Note note = Note.fromJsonString(payload);
//You can then use your Note object however you want.
//e.g
print(note.title); // Hello
print(note.description); // This is my first reminder
}
关于flutter - 是否可以在 onSelectNotification 上为 flutter_local_notification 插件传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60124063/