简体   繁体   中英

How can we get value from future method in flutter?

I have this function returning the "SharedPreference" value stored in it.

  Future<bool> getLoginStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final loggedInStatus = prefs.getBool("loggedInStatus");

    if (loggedInStatus == null) {
      return false;
    }
    return loggedInStatus;
  }

Above function is in the class named "Constants.dart". When I do the test of extracting value from "getLoginStatus()" function by simple printing in different class.

 print("Login status : " + Constants().getLoginStatus().toString());

It give me below as an output. Why "Instance of 'Future'"? Why not simple either true or false?

I/flutter (19683): Login status : Instance of 'Future<bool>'

Since your getLoginStatus() is asynchronous and it return a bool value in future. So to get the value you have to await for the process to return it.

So the correct Code to retrieve the value would be:

bool loggedInStatus = await Constants().getLoginStatus();
print(loggedInStatus);

you can get data using await.

var data  = await Constants().getLoginStatus();
print(data);
getLoginStatus().then((val){ print("Login status : $val"});

The then function should be used with Futures to access the value returned from a future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM