Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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,
),
like image 767
Abdul Shabani Avatar asked Mar 13 '19 20:03

Abdul Shabani


2 Answers

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.

like image 67
Frank Treacy Avatar answered Jan 03 '23 19:01

Frank Treacy


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

like image 42
Mrak Vladar Avatar answered Jan 03 '23 21:01

Mrak Vladar