Future Builder is taking forever to fetch image in flutter

1.2k views Asked by At

This is the _getImage method which retrieves the download link of image from firebase storage & then this download string.

Future<String> _getImage(String filePath) async {
    var _urlImage = await FirebaseStorage.instance
        .ref()
        .child(filePath)
        .getDownloadURL();

    return _urlImage;
}

Now this is the future builder which will retrieve the image. blogs[index].pic1 contains the reference of firebase storage pic filepath and it's correct.

FutureBuilder<String>(
    future: _getImage(blogs[index].pic1), // async work
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.waiting: return Text('Image Loading....',style: TextStyle(fontSize: 10),);
      default:
        if (snapshot.hasError)
          return Text('Error: ${snapshot.error}');
        else
          return Image.network(snapshot.data.toString());
    }
  },
),

No, error message is shown, but ConnectionState.waiting is always true. Please help.

This is what console shows

I/zygote64(20385): Background concurrent copying GC freed 546604(21MB) AllocSpace objects, 134(2MB) LOS objects, 24% free, 74MB/98MB, paused 70us total 509.383ms
2

There are 2 answers

1
Alex.F On

The future parameter in the FutureBuilder should be a stored variable so that when FutureBuilder rebuilds it will not get a new future each time. Store the result of _getImage in a stateful widget (initialized in initState for example) and pass it to the builder.

0
Balaji Ks On
FutureBuilder<String>(
    future: _getImage(blogs[index].pic1),
    builder: (BuildContext context, AsyncSnapshot<Welcome> snapshot) {
      if (snapshot.hasData) {
        print("Success");
        return Text("Success!!!")
      } else if (!snapshot.hasData) {
         return Container(
            child: CircularProgressIndicator(),
          );
      } else if (snapshot.error) {
        print("error");
      } else {
        return Container(
            child: CircularProgressIndicator(),
          );
      }
    });

Use this method dude