Flutter: can't initialize shared preferences with workmanager


As the title say, I’m using 2 plugins, workmanager and shared preferences. The workmanager part works as it’s supposed to, while I get an error from shared preferences.

This is part of my code which has to do with the workmanager plugin:

void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) async {
    switch (taskName) {
      case 'midnight_task':
        try {
          await SharedPrefsHelper().initSharedPrefsInstance(); //THIS line causes the error
          await PedometerService.midnightTask();
          print('workmanager_service.dart: looks like midnightTask got successfully executed :D');
        } catch (e) {
          print('workmanager_service.dart midnightTask error: $e');
        print('workmanager_service.dart callbackDispatcher(): unhandled taskName: $taskName');
    return Future.value(true); // "The task is successful"

This is part of my code which deals with shared preferences:

SharedPreferences _prefs;

  Future<void> initSharedPrefsInstance() async {
    if (_prefs == null) _prefs = await SharedPreferences.getInstance(); //the error gets thrown here
    print('shared prefs initialized()');

  //this will NOT persist data
  Future<void> initSharedPrefsInstanceMock() async {
    SharedPreferences.setMockInitialValues({}); //<- this line: only difference to above method
    if (_prefs == null) _prefs = await SharedPreferences.getInstance();
    print('initSharedPrefsInstanceMock: shared prefs initialized()');

The following error gets thrown at the line specified by the comment:
workmanager_service.dart midnightTask error: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences).

I’ve tried this from another stackoverflow question (second method in the previous code sample) and it does NOT throw the error then, but as that guy said, it doesn’t persist data so it’s useless. I’ve also tried the other things he suggested (editing /android/app/build.gradle), and also many other things suggested by other people, but nothing worked for me.

Does anyone know what I can do to solve this problem?


This is due to a change in the implementation of shared_preferences, see this issue for discussion.

For now you can manually run the plugin’s Dart registration before using it in an isolate:

if (Platform.isAndroid) SharedPreferencesAndroid.registerWith();
if (Platform.isIOS) SharedPreferencesIOS.registerWith();

You will need to add direct dependencies on shared_preferences_android and shared_preferences_ios to use those classes.

Answered By – smorgan

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *