Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of 'Future<String>' instead of showing the value

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}'),))
like image 984
geek man Avatar asked Jan 27 '19 15:01

geek man


3 Answers

If you don't have the option to use await or async you can do the following.

getPhone().then((value){
 print(value);
});

and then assign a variable to them. From that, you'll have the result from the value.

like image 151
Carl Angelo Angcana Avatar answered Sep 19 '22 20:09

Carl Angelo Angcana


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(),))
  }
like image 35
Günter Zöchbauer Avatar answered Sep 18 '22 20:09

Günter Zöchbauer


Calling a function that returns a Future, will not block your code, that’s why that function is called asynchronous. Instead, it will immediately return a Future object, which is at first uncompleted.

String phoneOfPatient;

Future<void> getPhone() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final String patientPhone = await /*added */ prefs.getString('patientPhone');

}

And after func call like this. The result of the Future is available only when the Future is completed.

You can access the result of the Future using either of the following keywords:

then

await

You can consume the result of this function in either of the following ways:

getphone.then((value) =>  {
  print(value);               // here will be printed patientPhone numbers.
  phoneOfPatient = value;
});

Or

Future<void> foo() async {
  String phoneOfPatient = await getphone();
  print(phoneOfPatient);        // here will be printed patientPhone numbers.
}
like image 36
Paresh Mangukiya Avatar answered Sep 21 '22 20:09

Paresh Mangukiya