是否可以在 onSelectNotification 上为 flutter_local_notification 插件传递参数

Wei*_*Jun 3 notifications push-notification flutter

抱歉,我是 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);
Run Code Online (Sandbox Code Playgroud)

Vic*_*ele 5

您可以将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,
        };
    }
Run Code Online (Sandbox Code Playgroud)

现在,要设置通知,您可以从模型创建 JSON 字符串并将其作为 传递payloadflutterLocalNotificationsPlugin如下所示的方法:

    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);
Run Code Online (Sandbox Code Playgroud)

接下来你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

    }
Run Code Online (Sandbox Code Playgroud)