0

My application has an input that receives a link to retrieve an image from the internet, but if the user enters an invalid link, the app breaks.

I'm currently using Image.network() to make the image request.

How to handle this exception?

child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network(imageController.text, fit: BoxFit.cover,) ),

Error generated: Error generated

Resolve the error and handle the thrown exception.

2 Answers2

0

You can check this answer and use error builder.
You can also in your case check a variable using terniary operator:

child: imageController.text.isNotEmpty ? ClipRRect( borderRadius: BorderRadius.circular(10),   child: Image.network(imageController.text, fit: BoxFit.cover,), ) : const SizedBox(),
0

Solution

you have to future function that check the url

try {
  Image.network('https://example.com/wrong-url.jpg');
} catch (e) {
  // Error handling code
  print('Error: $e');
  // Display a custom error message or fallback widget
  // For example:
  return Text('Invalid URL or Failed to load image');
}

and return it in FutureBuilder also You can use onErrorBuilder

Image.network(
      imageUrl,
      errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
        // Custom error widget to display when image loading fails
        return Text('Failed to load image');
      },
      loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
        if (loadingProgress == null)
          return child; // Image is still loading, return default placeholder
        return CircularProgressIndicator(); // Show a loading indicator
      },
    );

If you choose to use FutureBuilder you can handle all the error in your function

FutureBuilder<void>(
      future: yourFunction()
      builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // Image loaded successfully
          return Image.network(imageUrl);
        } else if (snapshot.hasError) {
          // Error occurred while loading image
          return Text('Failed to load image');
        } else {
          // Image still loading
          return CircularProgressIndicator();
        }
      },
    );
Ayoub Ali
  • 91
  • 1
  • 4