[Solved] Instance of 'Future<String>' instead of showing the value

Question

Asked by geek m on January 27, 2019 (source).

Iam using flutter and I am trying to get a value from shared_preferences that I had set before, and display it in a text widget. but i get Instance of Future<String> instead of the value. here is my code:

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

Answer

Question answered by Günter Z (source).

There is await missing before prefs.getString( and use setState() instead of returning the value. build() can't use 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(),))
  }
DART FLUTTER FUTURE
SHARE: