Flutter:共享首选项在启动时为null

Flutter:共享首选项在启动时为null,第1张

Flutter:共享首选项在启动时为null

您的问题是您快速连续调用load()和printMyBool()。由于load()是异步调用,因此它尚未执行任何代码,因此仅对其进行了调度。因此,printMyBool在加载主体之前执行。

无需将静态函数放在类中-只需将它们声明为顶级函数即可。另外,您实际上并不希望_myBool是全局变量-
它应该是Widget状态的一部分。这样,当您更新它时,Flutter知道要重绘树的哪些部分。

我已经对您的代码进行了重组,以删除多余的静态变量。

import 'package:flutter/material.dart';import 'package:shared_preferences/shared_preferences.dart';void main() => runApp(new MyApp());class MyApp extends StatefulWidget {  MyApp({Key key}) : super(key: key);  @override  createState() => new MyAppState();}const EdgeInsets pad20 = const EdgeInsets.all(20.0);const String spKey = 'myBool';class MyAppState extends State<MyApp> {  SharedPreferences sharedPreferences;  bool _testValue;  @override  void initState() {    super.initState();    SharedPreferences.getInstance().then((SharedPreferences sp) {      sharedPreferences = sp;      _testValue = sharedPreferences.getBool(spKey);      // will be null if never previously saved      if (_testValue == null) {        _testValue = false;        persist(_testValue); // set an initial value      }      setState(() {});    });  }  void persist(bool value) {    setState(() {      _testValue = value;    });    sharedPreferences?.setBool(spKey, value);  }  @override  Widget build(BuildContext context) {    return new MaterialApp(      home: new Scaffold(        body: new Center(          child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[   new Padding(     padding: pad20,     child: new Text(         _testValue == null ? 'not ready' : _testValue.toString()),   ),   new Padding(     padding: pad20,     child: new RaisedButton(       child: new Text('Save True'),       onPressed: () => persist(true),     ),   ),   new Padding(     padding: pad20,     child: new RaisedButton(       child: new Text('Save False'),       onPressed: () => persist(false),     ),   ),   new Padding(     padding: pad20,     child: new RaisedButton(       child: new Text('Print myBool'),       onPressed: () => print(_testValue),     ),   ), ],          ),        ),      ),    );  }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5129470.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存