GetStorage().read('userData'); returns null when I try to read it onStart method of flutter background service package.

I am using flutter background service package to to run background tasks even when application is in terminated state. I am using Get Storage package to store user data after the user successfully logs in to the application. And this works fine. What I want is when the user logs in to the application for the first time then in the onstart method of the flutter background service package, I want to read the user data which is stored to local storage using get storage package. The only issue i am having is that in onstart method of flutter background service when i try reading the user data when the user logs in to the application for the first time after installing the application or when user re logs in to the application after logging out then the user data returns null. However, when i hot restarts the application in my emulator without logging it out then it starts retrieving user data which is saved on local storage using get storage.

Here is my onstart method of flutter background service in main.dart and its a top tier function.

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async{
  DartPluginRegistrant.ensureInitialized();

  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) async{
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    service.stopSelf();
  });

  Timer.periodic(const Duration(seconds: 10), (timer) async{
    if(service is AndroidServiceInstance){
      await GetStorage.init();

      // Retrieve user data from local storage
      final userData = GetStorage().read('userData');
      if(userData != null){
        Logger().i('<<User data is : $userData>>');
      }
    }
  });
}

And here is how i am registering this task as background task after the user successfully logs into to the application

FlutterBackgroundService().invoke('setAsBackground');

Can anyone please tell me how to get user data which is saved on the local storage as soon as user logs in to the application? Any help or suggestion will be highly recommended.

0

There are 0 best solutions below