In the onSelected
function of a DropDownMenu
widget, a function which returns a Future
is called. After that Future
completes, a regular function must be executed. In order to do this, am using the then
keyword, as follows:
Serialize.deSerialize().then((e) => updateStatusbar());
The signature of the deserialize()
method is:
static Future<void> deSerialize() async {
Within this method, there are several asynchronous calls using the await
keyword, similar to the following:
await storage.read(key:'myKey');
The problem is that the updateStatusbar()
method is called before the deSerialize()
method has completed. I cannot call deSerialize()
using await
, because the DropDownMenu
is defined within the build()
method of widget, and that cannot be made async
.
Adding print statements to verify the order of execution shows the following:
flutter: inside deSerialize 1
flutter: inside deSerxialize 2
flutter: inside deSerialize 3
flutter: inside deSerialize 4
flutter: inside method called from deSerialize 1
flutter: end of deSerialize
flutter: in updateStatusbar 1
flutter: in updateStatusbar 2
flutter: inside method called from deSerialize 2
flutter: inside method called from deSerialize 3
flutter: inside method called from deSerialize 4
flutter: inside method called from deSerialize 5
flutter: inside method called from deSerialize 6
flutter: inside method called from deSerialize 7
flutter: inside method called from deSerialize 8
flutter: inside method called from deSerialize 10
flutter: end of methods called from deSerialize
Most of the functions called using await
within deSerialize()
are called after the ones in updateStatusBar()
.
What is the correct way to chain these function calls so that deSerialize()
only returns to then()
after all the functions called within deSerialize()
using await
have finished?
Thanks very much
2
Answers
The issue was that within the
deSerialize()
itself, I was not usingawait
to call the otherFutures
. Now it worksThe function
updateStatusBar
is called afterdeserialize
has completed.I would recommend restructuring your code and if the widget you are building depends on a Future value then rather use a
FutureBuilder
.Reply to comment: I still don’t understand the problem, since the
onSelected
callback of aDropDownMenu
can be markedasync
.