Search code examples
fluttersharedpreferences

Why getting the Instance of SharedPreferences is an async function? Is it a good practice to cache the instance?


I wonder why is SharedPreferences.getInstance() an async function?! I want to cache the instance in a static variable and use it to store settings data without having to use await or SharedPreferences.getInstance().then(...), but if they made it async, it should be for a good reason, any ideas?


Solution

  • SharedPreferences.getInstance() actually fetches the data and does not only provide a reference to a SharedPreferences's instance

    based on the source code

      static Future<SharedPreferences> getInstance() async {
        if (_completer == null) {
          _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;
          }
        }
        return _completer.future;
      }
    

    and

      static Future<Map<String, Object>> _getSharedPreferencesMap() async {
        final Map<String, Object> fromSystem = await _store.getAll();
        assert(fromSystem != null);
        // Strip the flutter. prefix from the returned preferences.
        final Map<String, Object> preferencesMap = <String, Object>{};
        for (String key in fromSystem.keys) {
          assert(key.startsWith(_prefix));
          preferencesMap[key.substring(_prefix.length)] = fromSystem[key];
        }
        return preferencesMap;
      }
    

    I don't know if this was trivial, but it wasn't for me, I thought data are being fetched only on get functions.