Flutter: Access Stored Sharedpreference value from Other Pages

Flutter shared preferences is actually implemented as an in-memory cache. The first time that you call SharedPreferences.getInstance() all the current values are read from NSUserDefaults (on iOS) and SharedPreferences (on Android) and cached in memory. This involves channels, so is async. The Future returns a singleton class that wraps this cache. Any subsequent calls to getInstance return this singleton class.

When you get a value from shared preferences the value is simply fetched from the in-memory cache. When you set a value the cache is immediately updated and an async method started to write it back to the operating system. (You can wait for confirmation of completion of that, but you don’t have to.) Note that the reads and writes from and to the cache are synchronous, so you have immediate access to that cache of settings. (It may take a moment to reach the operating system so the in-memory cache isn’t guaranteed to match the device preferences, but this should only happen under error conditions.)

The reason why this is interesting is that once you get the result of SharedPreferences.getInstance() you can read and write values synchronously. Since the instance is singleton it seems reasonable to keep a copy of it. In particular, you can make your main async and fetch it there.

SharedPreferences sp;

void main() async {
  sp = await SharedPreferences.getInstance();
  runApp(new MyApp());

This allows you to refer to sp throughout your code:

  onPressed: () {
    sp.setString('abc', 'def');

knowing that the in-memory cache is consistent. In particular, any values set in one page can be got in another page following navigation.

Having said all that, you should probably think of your stored preferences as just one part of your state, which just happens to get initialized at startup and on setting it fires off a background task to persist it automatically. You could then deal with the preferences in the same way as the rest of your state however you are doing that (InheritedWidget + controller, Redux, Streams, etc.).

Leave a Comment