简体   繁体   中英

How to get primitive value from Future object (Future<int>) in flutter?

I am getting Future instance while getting sharedPreference value as follows

 Future<int>  getCounterValue() async{
    SharedPreferences preferences= await SharedPreferences.getInstance();
    return preferences.getInt("counter") ;
   }

Then I want to get int value from that Future instance. Please help thanks in advance.

There is no way to get back from async execution to sync execution.

You can only get the value by using await or .then((param) { print(param); })

You would need to provide more context to make a concrete suggestion about how to solve your actual problem.

For non-async method:

void methodSync() {
  getCounterValue().then(
    (value){
      // do something with value
      print(value);
    }
  );
}

For async method:

void methodAsync() async{
  int value = await getCounterValue();
  // do something with value
  print(value);
}

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