Flutter: Shared Preferences null on Startup

前端 未结 6 1085
刺人心
刺人心 2021-01-11 12:28

Problem: Shared preference bool value is null on startup even though I have given it a value if prefs.getBool(\'myBool\') returns null

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-11 13:33

    import 'package:shared_preferences/shared_preferences.dart';
     
    class MySharedPreferences {
      MySharedPreferences._privateConstructor();
     
      static final MySharedPreferences instance =
          MySharedPreferences._privateConstructor();
     
      setBooleanValue(String key, bool value) async {
        SharedPreferences myPrefs = await SharedPreferences.getInstance();
        myPrefs.setBool(key, value);
      }
     
      Future getBooleanValue(String key) async {
        SharedPreferences myPrefs = await SharedPreferences.getInstance();
        return myPrefs.getBool(key) ?? false;
      }
     
    }
    
    MySharedPreferences.instance
            .getBooleanValue("key")
            .then((value) => setState(() {
                  val result = value;
                }));
    

    For more reference: Flutter Shared Preferences Tutorial

提交回复
热议问题