As a brief note, sometimes in Flutter (and Dart) you have to write a method/function that makes an asynchronous call, but the method can’t be marked async
itself. The Flutter initState
method is a good example of this.
So far I’ve learned two ways to deal with this:
- Use
then
inside the non-async method - Use an unusual anonymous-function style syntax inside the method
I’ll demonstrate each technique below.
(1) Use `then` inside the non-async method
The first style is what I normally use. For instance, the initState
method can’t be marked async
, but in this example the _readImageFilesFromFilesystem
method is an async
method. So my solution is to call then
on that async method, and that solves the problem:
@override
void initState() {
super.initState();
_readImageFilesFromFilesystem().then((listOfImageFiles) {
// work with the listOfImageFiles inside
// this code block
});
}
(2) Use an unusual anonymous-function style syntax inside the method
Another approach I just learned is to use this somewhat unusual-looking anonymous function style that I just saw in this article:
@override
void initState() {
super.initState();
() async {
_permissionStatus = await Permission.storage.status;
debugPrint('DEBUG: _permissionStatus = $_permissionStatus');
if (_permissionStatus != PermissionStatus.granted) {
PermissionStatus permissionStatus= await Permission.storage.request();
setState(() {
_permissionStatus = permissionStatus;
});
}
} (); // NOTE: '()' may be an error
}
I believe it’s correct to call that code an anonymous function, or more accurately, an anonymous async function.
At the moment I’m not sure why that last ()
is in the code; I think it may be an error, because the code works without it.
But going back to the purpose of this blog post, I can verify that this is another way to run async
code inside a method that can’t be marked as an async
method, such as initState
.
Summary
In summary, if you ever have to use async
code inside a non-async method like `initState, I hope these examples and techniques are helpful. Like any other code, be sure to test them, but both techniques appear to be working properly in my latest Flutter application.