简体   繁体   中英

How use var from out side SharedPreferences function Flutter

i save font size with SharedPreferences and when print (myfont) in (initstat) data was Null . and anywhere outside getprefs() . why ?

i use this code

  class MyASetting extends State<SettingPage> {
bool checkfont = true;
double myfont  ;

saveprefs(bool val) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
  checkfont = val;
  prefs.setBool("checkfont", checkfont);
  getprefs();
 });
  } // save sharde

  getprefs() async {
  try {
   SharedPreferences prefs = await SharedPreferences.getInstance();
   setState(() {
     checkfont = prefs.getBool("checkfont");
    if (checkfont == true) {
      myfont = 20;
    } else {
      myfont = 16;
    }
    return myfont;
  });
} catch (e) {
  print("Sorry");
}
 } // get shared

 @override
 void initState() {
   super.initState();
   print(myfont);
   getprefs();
   }

put this outside setState scope

  prefs.setBool("checkfont", checkfont);

your final code must be :

saveprefs(bool val) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool("checkfont", val);
  setState(() {
    checkfont = val;
  // getprefs();
  });
} // save sharde

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM