颤抖:抛出了另一个异常:在构建期间尝试获取SharedPreference实例时调用了setState()或markNeedsBuild()

时间:2020-08-15 13:58:31

标签: flutter sharedpreferences

我有一个要求,我需要从sharedPreferences获取该条件的代码,因此,我正在执行下面的工作,但是它被认为是不好的作法,或者我应该说颤抖正在推动警告。

 @override
  void didChangeDependencies() async {
    _prefs = await SharedPreferences.getInstance();
    if (langCode == null) {
      setState(() {
        langCode = "${_prefs.get('langCode')}-${_prefs.get('countryCode')}";
      });
    }
    super.didChangeDependencies();
  }


通常,我会创建async函数,并在initState()中调用它,但同时也会出现相同的错误。

如果我在stateState()中不使用didChangeDependencies(),则langCode的值未设置,我得到了flutter: Another exception was thrown: NoSuchMethodError: The method 'get' was called on null

在我的情况下,什么是避免以下错误的最佳解决方案?

flutter: Another exception was thrown: NoSuchMethodError: The method 'get' was called on null.
flutter: Another exception was thrown: setState() or markNeedsBuild() called during build.

感谢您回答我的问题。

2 个答案:

答案 0 :(得分:0)

 if you dont want to use async function you want to remove only null error just use 
 null avoid operator 
  "${_prefs?.get('langCode')}-${_prefs.get('countryCode')??""}";
  

或者您可以这样使用

Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

@override
void initState() {
super.initState();
 getData()
}

getData()async{
   final SharedPreferences prefs = await _prefs;
   String auth =   prefs.getString('auth');
   String uid =    prefs.getString('uid');

}

答案 1 :(得分:0)

如果您在启动应用时调用共享首选项,则必须等待初始化,如文档中所述link

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // above line must be called before runApp();
  var prefs = await SharedPreferences.getInstance();
  runApp(MyApp());
}

然后,您可以在其他Widget中使用stf或stl。如果答案有帮助,请投票。