0

I have a strange problem. I need the value of a Future<String> as String to display an image with CachedNetworkImage. Because I have to wait for a downloadUrl which comes from Firebase Storage I found no way to use it as normal String.

Here is my Widget where I need the value

Container(child: Obx(
  () {
    return CachedNetworkImage(
        imageUrl: _getImage(), // Here I need the value as String
        height: Get.height,
        fit: BoxFit.cover);
  },
))

And this is my _getImage() function

Future<String> _getImage() async {
  var url = return await MyStorage().getDownloadUrl(url);
  return url;
}

The getDownloadUrl() only returns a String with the download url from Firebase Storage

Future<String> getDownloadUrl(ref) async {
    final StorageReference storage = FirebaseStorage().ref().child(ref);
    final url = await storage.getDownloadURL();

    return url.toString();
}

Because I definitely have to wait for the getDownloadUrl() I have no chance to return the value as String. But I need it as String. Otherwise I get an error.

How would you solve this problem?

Vueer
  • 1,432
  • 3
  • 21
  • 57
  • Try using FutureBuilder. Widget that computes future method first, and afterwards let you build your wanted widget with given value from future. https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html – David Sedlář Oct 16 '20 at 11:09
  • 1
    Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – void Oct 16 '20 at 11:17

1 Answers1

1

A FutureBuilder will build the UI depending on the state of the Future. All you have to do is check if it has the data, then build the image.

  Future<String> myFutureString() async {
    await Future.delayed(Duration(seconds: 1));
    return 'Hello';
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: myFutureString(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Container(
            child: Text(snapshot.data),
          );
        }
        return CircularProgressIndicator();
      },
    );
  }
Benjamin
  • 5,783
  • 4
  • 25
  • 49