gee*_*man 9 future dart flutter
我正在使用颤振,我试图从我之前设置的 shared_preferences 中获取一个值,并将其显示在文本小部件中。但我得到 Instance ofFuture<String>
而不是值。这是我的代码:
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}'),))
Run Code Online (Sandbox Code Playgroud)
有await
前失踪prefs.getString(
和使用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(),))
}
Run Code Online (Sandbox Code Playgroud)
小智 7
如果您没有使用该选项,await
或者async
您可以执行以下操作。
getPhone().then((value){
print(value);
});
Run Code Online (Sandbox Code Playgroud)
然后为它们分配一个变量。由此,您将获得 的结果value
。
归档时间: |
|
查看次数: |
11456 次 |
最近记录: |