Reputation: 1007
Does Dart have a method to wait for a function to return a true/false then call the next function after it?
I have seen similar questions here, but I cannot seem to get them to work in a way to achieve my goal. Some of the answers use explicit delayed time (.e.g wait 3 seconds). But this doesn't work for my method.
E.g.
print('START');
await fetchResults();
print('COMPLETE'); // This is not called until the fetchResults returns true/false
NOTE: I have tried something like:
Future<bool> fetchResults() {
await Future.doWhile(() => return true);
}
But this puts my function in infinite loop.
Upvotes: 2
Views: 8388
Reputation: 903
You need to use two async function for that
Future<void> execute()async {
print('START');
final result = await fetchResults();
print('COMPLETE'); // This is not called until the fetchResults returns true/false
}
Future<bool> fetchResults() async {
// Your fetchResult logic here
// e.g:
final int result = 1+1;
print('In between');
if(result == 2) return true;
else return false;
}
Output
START
In between
COMPLETE
Upvotes: 1
Reputation: 9744
In an async
function you can use await
to wait for a function call to be completed and get its result. This will wait 3 seconds before printing COMPLETE
:
void waitForIt async {
print('START');
if (await (fetchResults())) {
print('COMPLETE');
}
}
Future<bool> fetchResults() async {
return Future.delayed(const Duration(milliseconds: 3000), () {
return true;
});
}
But it is also possible that your fetchResults
is not async, but sync. The following produces the same 3 seconds delay:
import 'dart:io';
bool fetchResults() {
sleep(Duration(seconds: 3));
return true;
}
Upvotes: 2