简体   繁体   English

如何从外部SharedPreferences函数Flutter中使用var

[英]How use var from out side SharedPreferences function Flutter

i save font size with SharedPreferences and when print (myfont) in (initstat) data was Null . 我使用SharedPreferences保存字体大小,并且当(initstat)数据中的print(myfont)为Null时。 and anywhere outside getprefs() . 以及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 将此置于setState范围之外

  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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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