且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是正确的方法来获取已使用sharedPreferences存储到窗口小部件的值?

更新时间:2023-11-25 11:13:40

您的问题很简单,sharedPreferences会花一些时间来获取保存在其中的值,因为它已经调用了值构建函数,因此它给了您必须为Text小部件提供非null的String。 此错误。



解决方案
,所以请尝试初始化您的Srting名称= = / p>

或支票,

  Text(
name!= null?name:'',
样式:TextStyle(fontSize:20,fontWeight:FontWeight.bold),
),

,并且只要您的String准备好sharepref,就尝试调用setSate,

  sharepref。然后((onValue){
setState((){
mUserInfo = onValue;
});
}


What is the correct way to get the value which has been stored using sharedPreferences to widget?

PageA

 @override
  void initState() {
    super.initState();
    sharedPreferences = SampleSharedPreferences().getData();
    sharedPreferences.then((onValue) {
      name = onValue.name;  // I debug this line, I can see the value
    });
  }

     @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: SingleChildScrollView(
                child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              child: Text(
                name,
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              padding: const EdgeInsets.only(top: 14.0, left: 14.0),
            ),
              ....

Error

A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 269 pos 10: 'data != null'

I guess is because the widget is calling first before SharedPreferences get called? What is the proper way to write it?

SampleSharedPreferences

class SampleSharedPreferences {

  static const NAME = "user_name";

  void store(ABC abc) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(NAME, name);
  }

  Future<ABC> getUser() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    ABC abc = new ABC();
    abc.name = prefs.getString(USER_NAME);
    return abc;
  }
}

Your problem is simple sharedPreferences takes some time to fetch values saved in it, by the time it fetches the value build function is already called and hence it gives you A non-null String must be provided to a Text widget. this error.

Solution: so either try to initialize your Srting name=""

or check,

Text(
  name!=null? name:'',
  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
  ),

and whenever sharepref is ready with your String try to call setSate,

 sharepref .then((onValue) {
      setState(() {
        mUserInfo = onValue;
      });
    }