I’m currently new to Flutter and Dart. I have functions that need to be finished before another function is executed. Is it reasonable to use Future Delayed to delay that specific function? Is there another method of doing it?
The function that I want to delay needs specific data from the previous function, and when it executes, it returns null values. Now, I want it to finish the first function before the following function executes.
3
Answers
No as you said it isn’t reasonnable to use the
Future.delayed
!Why? Because you will need to set a
Duration
and then there’s 2 options:1- the duration is too short, and the first function will not be finished
2- the duration is too long, and the user will wait (for nothing)
As the first function takes time (I suppose it’s a network call or a storage call), it probably returns a
Future<Something>
and isasync
. You have then 2 options:1- Use a callback when the
Future
is completed2- Use
await
keywordIt’s a matter of preference. My own preference is to use linear code style and use
await
keyword.You can lean more on
Future
andawait
here: https://dart.dev/codelabs/async-awaitThat is not how Future is supposed to work. Delays, will not ensure that the previous processes have finished, for that, you need to create either a listener or another type of controller to track if the first processes ended, or if they returned a valid response.
What you can do is this.
Here is one possible logic structure, to define your own process:
_first_process_ended == true
and_second_process_ended == true
launch Third process.Another possibility is to use Future methods:
No. Using delay isn’t a guaranteed or efficient way to do it.
Why? Because the first async function could complete before or after the delay duration depending on system, network and other factors.
Solution?
Use then() or await on both functions.
1.