Flutter beginner here; I'm getting this error: type 'Future<dynamic>' is not a subtype of type 'String'
Function that fetch download url from firebase storage
_getImageUrl(var fileName) async {
print(fileName);
final StorageReference ref = FirebaseStorage.instance.ref().child('categories/' + fileName);
Uri downloadUrl = await ref.getDownloadURL();
var url = downloadUrl.toString();
return url;
}
where I called the function
child: Image(
image: AdvancedNetworkImage(
_getImageUrl(menuItem['image'].toString()),
timeoutDuration: Duration(minutes: 1),
useDiskCache: true,
cacheRule: CacheRule(maxAge: const Duration(days: 7)),
),
height: mediaQuery.size.width * 0.22,
width: mediaQuery.size.width * 0.22,
),
You cannot use async/await
when returning from a build
method (or a builder
closure). Any time you have async when building the widget tree, it's best to use a FutureBuilder
:
child: FutureBuilder<String>(
future: _getImageUrl(menuItem['image'].toString()),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Image(
image: AdvancedNetworkImage(
snapshot.data,
timeoutDuration: Duration(minutes: 1),
useDiskCache: true,
cacheRule: CacheRule(maxAge: const Duration(days: 7)),
),
height: mediaQuery.size.width * 0.22,
width: mediaQuery.size.width * 0.22,
);
}
return CircularProgressIndicator();
}
),
Alternatively, you could use a StatefulWidget
for this but it's much more boilerplate. There are more details and a live sample at https://flutterigniter.com/build-widget-with-async-method-call/ if you're interested.
Firstly Flutter returns a Future<type>
when the asynchronous
functions is not completed, when it is completes it will return data of the type type
. The mistake you are making is calling an asynchronous
from a synchronous
function. Although dart will execute the functions asynchronously
(You can validate this by printing the url from the asynchronous
function).
But the place you are calling it from is not waiting for the asynchronous
function to finish.
I hope it is clear now.
For more clarity visit Asynchronous Programming
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With