'How to fix type 'Future<dynamic>' is not a subtype of type 'String' Flutter

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,
),


Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank Treacy
Solution 2