11
votes

Shared_preferences (https://pub.dev/packages/shared_preferences) doesn't seem to work for Flutter for Web.

I have the following function that's called when a button is pressed.

 getEmail() async {
    print("reached 1st line");
    SharedPreferences prefs = await SharedPreferences.getInstance();
    print("reached 2nd line");
    String _confirmedEmail = prefs.getString('_confirmedEmail') ?? "";
)

It prints "reached 1st line" but not "reached 2nd line", which means the program doesn't go past the await statement. Interestingly I don't get any error either. It seems to just ignore the rest of the function after the await statement.

What is the best alternative to store shared preferences in Flutter for Web?

4

4 Answers

21
votes

Great news, from version 0.5.6 shared_prefs flutter supports web by default

Now it's includes shared_preferences for web

Your code should work without changes, just update dependency in pubspec.yaml

dependencies:
 shared_preferences: ^0.5.6
4
votes

shared_preferences are not supposed to work with flutter web, that's why value of instance never returns. For this purpose, you can use any key-value stores instead, for example, sembast

UPD: the package supports web now since version 0.5.6

1
votes

I think it is supported now due to this. It depends on shared_preferences_web image from pub dev

0
votes

You probably check the tags when you search for a library in pub.dev.

For the web the best way to implement that is implementing cache for web and dcache for implement that using flutter_web.

import 'package:dcache/dcache.dart';

void main() {
  Cache c = new SimpleCache(storage: new SimpleStorage(size: 20));

    c.set("key", 42);
    print(c.get("key")); // 42
    print(c.containsKey("unknown_key")); // false
    print(c.get("unknown_key")); // nil
}

As you can see, is very similar to shared_preferences for Flutter.

Hope this could help.