1

I just want to ask if is there a better way to know if an image successfully loads and then place it in a bool state using Riverpod?

Right now I have this code that looks like this:

final validPhotoProvider = StateProvider<bool>((ref) => false);

Image.network(
   photoUrl, 
   loadingBuilder: (context, child, loadingProgress){
      if(loadingProgress == null){ //means image has finished loading.
        ref.read(validPhotoProvider).state = true;
        return child;
      }
      return CircularProgressIndicator();
   },
),

As you can see I am relying on the builder to know if the image was loaded. Is there a better way to do this as I know this kind of method is not good as it may result in a bad state eventually.

ejandra
  • 336
  • 2
  • 4
  • 15

1 Answers1

0

So I solved this when I found this question.

What I did was change the code to something like this:

final validPhotoProvider = StateProvider<bool>((ref) => false);

Widget build(context, ref){

Image? image;
    if (photoUrl != null) {
      image = Image.network(
        photoUrl,
      );
      image.image
          .resolve(const ImageConfiguration())
          .addListener(ImageStreamListener((info, call) {
        if (mounted) {
          ref.read(validPhotoProvider).state = true;
        }
      }));
}

return Image.network(
   photoUrl, 
);
...
}

What you have to do is actually add a listener to the image stream. As someone new in Flutter, this is new knowledge to me and I hope this can help people who might run into the same issue.

ejandra
  • 336
  • 2
  • 4
  • 15