我正在使用 flutter,我正在尝试从我之前设置的 shared_preferences 中获取一个值,并将其显示在文本小部件中。但我得到 Future<String>
的实例而不是值(value)。这是我的代码:
Future<String> getPhone() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String patientPhone = prefs.getString('patientPhone').toString();
print(patientPhone);
return patientPhone;
}
Future<String> phoneOfPatient = getPhone();
Center(child: Text('${phoneOfPatient}'),))
最佳答案
在 prefs.getString(
之前缺少 await
并使用 setState()
而不是返回值。 build()
不能使用 await
。
String _patientPhone;
Future<void> getPhone() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String patientPhone = await /*added */ prefs.getString('patientPhone');
print(patientPhone);
setState(() => _patientPhone = patientPhone);
}
build() {
...
Center(child: _patientPhone != null ? Text('${_patientPhone}') : Container(),))
}
关于flutter - 'Future<String>' 的实例而不是显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54389775/