Flutter-如何通过非异步方法从共享的首选项中获取价值 [英] Flutter - How to get value from shared preferences in a non-async method
问题描述
我正在尝试从类的getter方法获取保存在 SharedPreferences
中的某些值。但是 SharedPreferences.getInstance()
返回 Future
。有没有一种方法可以在非 async
的getter方法中获取 SharedPreferences
对象,例如:
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");
}
}
Dart中是否有类似于<$ C#中的c $ c> .Result 属性,例如 getSomethingAsync()。Result
( https://docs.microsoft.com/zh-CN /dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.7.2 )?
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)?
推荐答案
您可以在 initState()
中执行此操作,然后在调用 setState()
来更新您的 build()
方法。其他方法是使用 FutureBuilder()
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);
});
}
这篇关于Flutter-如何通过非异步方法从共享的首选项中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!