[英]Can't figure it out how to use SharedPreferences in flutter, please help :)
[英]How use var from out side SharedPreferences function Flutter
我使用SharedPreferences保存字体大小,并且当(initstat)数据中的print(myfont)为Null时。 以及getprefs()之外的任何地方。 为什么呢?
我用这个代码
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();
}
将此置于setState范围之外
prefs.setBool("checkfont", checkfont);
您的最终代码必须是:
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.