Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot catch NetworkImageLoadException when Image.network() failed

I use Image.network() to show image from URL this is how I use it

Image image = Image.network(
      _auth.currentUser!.photoURL!,
      width: 100.getWidth(context),
      height: 100.getWidth(context),
      frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
        return wasSynchronouslyLoaded
            ? child
            : _profileImagePlaceholder(context);
      },
      loadingBuilder: (context, child, loadingProgress) {
        return loadingProgress == null
            ? child
            : _profileImagePlaceholder(context);
      },
      errorBuilder: (context, error, stackTrace) {
        return _profileImagePlaceholder(context);
      },
    );

But even when I set errorBuilder or even wrap the whole thing with try/catch This NetworkImageLoadException still show

Full Exception

The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 403,


When the exception was thrown, this was the stack:
#0      NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:99:9)
<asynchronous suspension>
...

Image provider:
  NetworkImage("https://firebasestorage.googleapis.com/v0/b/biddee-co.appspot.com/o/profiles%2FdefaultProfile.png?alt=media&token=a4a99031-aabd-4597-b075-77ecb2d3e594",
  scale: 1.0)
Image key:
  NetworkImage("https://firebasestorage.googleapis.com/v0/b/biddee-co.appspot.com/o/profiles%2FdefaultProfile.png?alt=media&token=a4a99031-aabd-4597-b075-77ecb2d3e594",
  scale: 1.0)
like image 718
Fei Whang Avatar asked Jul 05 '26 09:07

Fei Whang


1 Answers

None of these would work for me with the current release of Flutter. This is what worked for me.

import 'package:http/http.dart';
...
final String url;
...
class _WebIconState extends State<WebIcon> {
  late Widget imgWidget;
  late bool loaded;

  @override
  void initState() {
    imgWidget = SizedBox.shrink();
    loaded = false;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Uri? uri = Uri.tryParse(widget.url);
    if (uri == null) {
      return SizedBox.shrink();
    }
    if (!loaded) {
      () async {
        Response resp = await get(uri);
        if (resp.statusCode >= 200 &&
            resp.statusCode < 300 &&
            resp.headers["content-type"] is String &&
            resp.headers["content-type"]!.contains("image")) {
          setState(() {
            imgWidget = Image.memory(resp.bodyBytes);
            loaded = true;
          });
        }

        log("Loaded ${widget.url}");
      }();
    }

    return imgWidget;
  }
like image 169
sleepwalk Avatar answered Jul 08 '26 02:07

sleepwalk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!