Search code examples
flutterflutter-sharedpreferenceawesome-notifications

Flutter: How to get/write data from/to shared preferences from action button's click using Awesome notifications?


I am using Awesome notifications to display notifications in my app. In the notifications, I have an action button, and when pressing it, the app is supposed to read and write some simple data from/to the memory of the phone using shared preferences. This is supposed to happen in the background without opening the app in the foreground.

I tried the following code:

  @pragma("vm:entry-point")
  static Future<void> onActionReceivedMethod(ReceivedAction action) async {
    print('It works');
    print(action.toMap());

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    List<PinnedFolder> pinnedList = [];
    try {
      final String? pinnedString = prefs.getString('pinnedKey');
      if (pinnedString != null) {
        pinnedList = PinnedFolder.decode(pinnedString);
        print('PinnedList got from memory, length: ${pinnedList.first.pinnedList.length}');
      }
    } catch (error) {
      debugPrint('Error: couldnt get pinned folders: $error');
    }

The "It works" and 'action.toMap()' get printed, but I can't get data from shared preferences. Is it so, that I can't use added packages in @pragma("vm:entry-point") functions? What would be the best way to fix the code? The action doesn't need to happen right after the button press, it can also happen the next time when the app is in the foreground, but so that the button action information is still available.


Solution

  • I found a solution using the package flutter_secure_storage.

    const storage = FlutterSecureStorage(); await storage.write(key: my_key, value: my_value);

    It seems to be so that only a few packages work in @pragma("vm:entry-point") functions, but this is one of them. I implemented it so that every time the app opens, it gets and handles the data from the secure storage before the app is launched.