Flutter SharedPreference do not persist

后端 未结 3 1288
长情又很酷
长情又很酷 2021-01-18 11:55

I want to save user preferences using Flutter\'s SharedPreference. But the registered preferences are ALL null at new start (when app have been closed, not unis

3条回答
  •  难免孤独
    2021-01-18 12:29

    import 'package:shared_preferences/shared_preferences.dart';
     
    class MySharedPreferences {
      MySharedPreferences._privateConstructor();
     
      static final MySharedPreferences instance =
          MySharedPreferences._privateConstructor();
     
      setStringValue(String key, String value) async {
        SharedPreferences myPrefs = await SharedPreferences.getInstance();
        myPrefs.setString(key, value);
      }
     
      Future getStringValue(String key) async {
        SharedPreferences myPrefs = await SharedPreferences.getInstance();
        return myPrefs.getString(key) ?? "";
      }
     
      Future containsKey(String key) async {
        SharedPreferences myPrefs = await SharedPreferences.getInstance();
        return myPrefs.containsKey(key);
      }
     
      removeValue(String key) async {
        SharedPreferences myPrefs = await SharedPreferences.getInstance();
        return myPrefs.remove(key);
      }
     
      removeAll() async{
        SharedPreferences myPrefs = await SharedPreferences.getInstance();
        return myPrefs.clear();
      }
     
    }
    

    For more reference: Flutter Shared Preferences Tutorial

提交回复
热议问题