[英]Is it possible to pass parameter on onSelectNotification for flutter_local_notification plugin
抱歉,我是 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
类:
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);
接下来,您在onSelectNotification
方法中获取payload
字符串并使用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.