Reputation: 111
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
Reputation: 1706
In general, the answer is NO
But, there are two points I want to add
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.
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
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