我正在使用flutter,我试图从之前设置的shared_preferences中获取一个值,并将其显示在文本小部件中。但是我得到了'Future'的实例而不是值。这是我的代码:

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}'),))

最佳答案

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(),))
  }

07-24 09:28