0

I am using the shared_preferences package. https://pub.dev/packages/shared_preferences/example

In my repository class, for each function, I am doing this to get the instance.

SharedPreferences prefs = await SharedPreferences.getInstance();

class AuthenticationRepository {

 Future<dynamic> logIn({required String email, required String password}) async {
     SharedPreferences prefs = await SharedPreferences.getInstance(); <--------
     ....
     prefs.clear();

     prefs.setString('user', encodedUser);
   }

   
 Future<String> logOut() async {

    SharedPreferences prefs = await SharedPreferences.getInstance(); <---------
    prefs.clear();
    if(prefs.containsKey('user')){
      return 'failed';
    }else{
      return 'cleared';
    }
  }

}
  1. I am just wondering if this is initiating a new sharedPreference object or as the function implies, we are only getting the same instance?

  2. Is there a better way to create the instance once, maybe as a class variable like below?

class AuthenticationRepository {
 
 SharedPreferences prefs = await SharedPreferences.getInstance();

 Future<dynamic> logIn({required String email, required String password}) async {

     ....
     this.prefs.clear();

     prefs.setString('user', encodedUser);
   }

   
  Future<String> logOut() async {


    this.prefs.clear();
    if(prefs.containsKey('user')){
      return 'failed';
    }else{
      return 'cleared';
    }
  }
}

Please advice, thanks in advance :)

Manas
  • 3,060
  • 4
  • 27
  • 55

1 Answers1

0
  1. Yes, you can get the same instance. In the shared_preference.dart file, there is a static value _completer. Here is getInstance() function. You can see the if (_completer == null), and it immediately returns a value when the _completer had been initialized.
static Completer<SharedPreferences>? _completer;

...

static Future<SharedPreferences> getInstance() async {
  if (_completer == null) {
    final completer = Completer<SharedPreferences>();
    try {
      final Map<String, Object> preferencesMap =
          await _getSharedPreferencesMap();
      completer.complete(SharedPreferences._(preferencesMap));
    } on Exception catch (e) {
      // If there's an error, explicitly return the future with an error.
      // then set the completer to null so we can retry.
      completer.completeError(e);
      final Future<SharedPreferences> sharedPrefsFuture = completer.future;
      _completer = null;
      return sharedPrefsFuture;
    }
    _completer = completer;
  }
  return _completer!.future;
}
  1. I think it is a better way to use the getInstance() function not to create another class.
MaNDOOoo
  • 1,347
  • 1
  • 5
  • 19