1
votes

I want to clear shared preferences when I send a FCM message and app is in background. Inside myBackgroundMessageHandler method I am calling a method to clear them.

static Future<dynamic> myBackgroundMessageHandler(
      Map<String, dynamic> message) {
     clearPreferences();
}

static void clearPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.clear();
}

I am getting the following error:

Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)

3
What if the app isn't on background? Does that still happens?Miguel Ruivo
@MiguelRuivo no, I have the shared preferences issue only when app is in background, since myBackgroundMessageHandler will not be called unless the app is in backgroundEddyG
Which version of Flutter are you at?Miguel Ruivo
Flutter 1.17.5 and Dart 2.8.4EddyG

3 Answers

0
votes

step 1) go to Application.kt/Application.java (in my case is kotlin)

step 2) add these line into Application class (in kotlin)

if (!registry!!.hasPlugin("io.flutter.plugins.sharedpreferences")) {
  SharedPreferencesPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin"));
}

remember import this as well

import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin

step 3) run flutter clean -> flutter get -> uninstall your app

0
votes

The code is completely fine.

Just restart your emulator. If you didn't do a full restart by closing the emulator and open it up again, this error can propably occur, because it doesnt have the newly added plugins.

0
votes

Add SharedPreferences.setMockInitialValues({}) to your code before the runApp() function inside the main function of Flutter App.
this fixed the error for me