Flutter - How to get value from shared preferences in a non-async method

那年仲夏 提交于 2020-12-01 09:28:25

问题


I am trying to get some values saved in the SharedPreferences from a getter method of a class. But SharedPreferences.getInstance() returns a Future. Is there a way to obtain the SharedPreferences object in a non-async getter methods, for example:

import 'package:shared_preferences/shared_preferences.dart';

class MyClass {
  get someValue {
    return _sharedPreferencesObject.getString("someKey");
  } 
}

Is there something in Dart that is similar to .Result property in C#, for example getSomethingAsync().Result (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.7.2)?


回答1:


You can do it in initState() and after this call setState() to update your build() method. Other way is to use FutureBuilder()

SharedPreferences sharedPrefs;

@override
void initState() {
  super.initState();
  SharedPreferences.getInstance().then((prefs) {
    setState(() => sharedPrefs = prefs);
  });
}



回答2:


You can use FutureBuilder()

SharedPreferences sharedPrefs;

@override
Widget build(BuildContext context) {
  return FutureBuilder(
    future: _getPrefs(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        return YourFinalWidget();
      }
      return CircularProgressIndicator(); // or some other widget
    },
  );
}

Future<void> _getPrefs() async{
  sharedPrefs = await SharedPreferences.getInstance();
}


来源:https://stackoverflow.com/questions/55402021/flutter-how-to-get-value-from-shared-preferences-in-a-non-async-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!