flutterbackgroundsharedpreferencesandroid-workmanagerflutter-workmanager

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');
        }
        break;
      default:
        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 {
    print('initSharedPrefsInstance()');
    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 {
    print('initSharedPrefsInstanceMock()');
    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?


Solution

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

    You need to run the plugin Dart registration before using plugins in an isolate:

    DartPluginRegistrant.ensureInitialized();