Saeed Farahi
Saeed Farahi

Reputation: 111

Run Future in sync in Flutter or Dart

I am kind of new to dart and flutter. I wanted to know how would someone run a Future synchronously? Is it possible at all?

Upvotes: 1

Views: 506

Answers (2)

Abdelazeem Kuratem
Abdelazeem Kuratem

Reputation: 1706

In general, the answer is NO

But, there are two points I want to add

  1. This was doable but in the dart:cli library using the waitFor keyword but now removed by the flutter team.

for more info, please check this Closed Issue

Also, there is another Open issue that requests this feature but in a different way Issue you can subscribe to it for any further updates in the future.

  1. You have some cases that you can deal with Futures as sync using SynchronousFuture.

For example, when you have some function that must return data local storage but it has a cache layer if you already fetched this data before then it will be stored in the memory

Future<String> getData(String key)async{
  if(_cache[key] != null) return _cache[key];

  return await _localStorage.load(key);
}

and get your data in main like this

void main() async {
  final output = await getData('myKey');
  print(output);
}

BUT instead of waiting it for both cases (local storage & cache) while the cache is exists right the way on the memory and there is no needs to await for it

We can do something like this using SynchronousFuture! 🎉

First, remove async keyword and start using SynchronousFuture!

Future<String> getData(String key){
  if(_cache[key] != null) return SynchronousFuture(_cache[key]);

  return _localStorage.load(key);
}

Next, use this Future method in the weirdest syntax ever you gonna see 😂 (But trust me it will work 😂🙏)!

void main() async {
  String? output;

  final myFuture = getData('myKey');
  myFuture.then((data) => output = data);
  
  // Yes I know we are trying to receive the data on then before awaiting to the future!
  if(output != null) 
    print(output);
  else 
    print(await myFuture);
}

This is only allowed with SynchronousFuture which makes the event loop run the then callback before moving to the next line in the current method.

Upvotes: 1

Gazihan Alankus
Gazihan Alankus

Reputation: 11984

No, it's not possible. If it was, then you would be able to freeze the UI thread until that Future is complete.

Upvotes: 2

Related Questions