欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Flutter 异常处理之图片篇

程序员文章站 2022-04-09 17:36:45
背景 说到异常处理,你可能直接会认为不就是 try catch 的事情,至于写一篇文章单独来说明吗? 如果你是这么想的,那么本篇说不定会给你惊喜哦~ 而且本篇聚焦在图片的异常处理。 场景 学以致用,有具体的应用场景,能够加深我们对知识的掌握。 我们以简书的文章列表为例,如下图: 假设产品有这样的需求 ......

Flutter 异常处理之图片篇

背景

说到异常处理,你可能直接会认为不就是 try-catch 的事情,至于写一篇文章单独来说明吗?

如果你是这么想的,那么本篇说不定会给你惊喜哦~

而且本篇聚焦在图片的异常处理。

场景

学以致用,有具体的应用场景,能够加深我们对知识的掌握。

我们以简书的文章列表为例,如下图:

Flutter 异常处理之图片篇

假设产品有这样的需求,当右边的封面图加载失败的时候,用一个默认图片替换或者直接让文本横向填充原有图片位置。

不管处理方式是怎样,首先我们要做的就是能够知道图片加载失败。

如何获知图片加载失败呢?下面我们通过 flutter 自带网络加载 api 和一个第三方网络库来进行对比说明。

image.network

我们看下源码,如下:

image.network(string src, {
    key key,
    double scale = 1.0,
    this.semanticlabel,
    this.excludefromsemantics = false,
    this.width,
    this.height,
    this.color,
    this.colorblendmode,
    this.fit,
    this.alignment = alignment.center,
    this.repeat = imagerepeat.norepeat,
    this.centerslice,
    this.matchtextdirection = false,
    this.gaplessplayback = false,
    this.filterquality = filterquality.low,
    map<string, string> headers,
  }) : image = networkimage(src, scale: scale, headers: headers),
       assert(alignment != null),
       assert(repeat != null),
       assert(matchtextdirection != null),
       super(key: key);

可以看到只有 src 是必填参数,因此我们给出 src 为不同值的情况。

1.一个图片的 url

  widget _buildwidget() {
    return image.network('https://upload-images.jianshu.io/upload_images/5361063-e413832da0038304.png?imagemogr2/auto-orient/strip%7cimageview2/2/w/800');
  }

能够正常显示如下图:

Flutter 异常处理之图片篇

2.不可访问 url,如随便一个字符串 test

  widget _buildwidget() {
    return image.network('test');
  }

终端报错如下:

flutter: ══╡ exception caught by image resource service ╞════════════════════════════════════════════════════
flutter: the following argumenterror was thrown resolving an image codec:
flutter: invalid argument(s): no host specified in uri file:///test

模拟器显示空白。

这种场景假设我们要捕获异常,增加 try-catch,如下:

  widget _buildwidget() {
    try {
      return image.network('test');
    } catch (e) {
      print('enter catch exception start');
      print(e);
      print('enter catch exception end');
      return container();
    }
  }

依然没法捕获

3.可访问非图片 url,比如 http://mp.weixin.qq.com/mp/homepage?__biz=mzi3otaynzawng==&hid=5&sn=7e4598d8b00537fe2846f2e85d746b9a&scene=18#wechat_redirect

  widget _buildwidget() {
    try {
      return image.network('http://mp.weixin.qq.com/mp/homepage?__biz=mzi3otaynzawng==&hid=5&sn=7e4598d8b00537fe2846f2e85d746b9a&scene=18#wechat_redirect');
    } catch (e) {
      print('enter catch exception start');
      print(e);
      print('enter catch exception end');
      return container();
    }
  }

控制台抛出如下异常

[verbose-2:codec.cc(97)] failed decoding image. data is either invalid, or it is encoded using an unsupported format.
flutter: ══╡ exception caught by image resource service ╞════════════════════════════════════════════════════
flutter: the following _exception was thrown resolving an image codec:
flutter: exception: operation failed

可以看到 try-catch 一样没法生效。没有打印相关日志。

cached_network_image

这是一个第三方开发的网络库,pub 地址为

因为项目有用到这个库,所以用这个来举例,并不是为其打广告,至于你实际开发是否用这个库,还是有其他更好的库,需要你自己去评估。

因为这个是项目组 ios 同事选择的,我这边并没有深入研究过。

我们仿照上面的依次执行 3 种 case。

1.一个图片的 url

  widget _buildwidget() {
    return image(image: new cachednetworkimageprovider('https://upload-images.jianshu.io/upload_images/5361063-e413832da0038304.png?imagemogr2/auto-orient/strip%7cimageview2/2/w/800'));
  }

能够正常显示如下图:

Flutter 异常处理之图片篇

2.不可访问 url,如随便一个字符串 test

  widget _buildwidget() {
    return image(image: new cachednetworkimageprovider('test'));
  }

终端报错如下:

flutter: ══╡ exception caught by image resource service ╞════════════════════════════════════════════════════
flutter: the following message was thrown resolving an image codec:
flutter: couldn't download or retrieve file.

模拟器显示空白。

这种场景假设我们要捕获异常,增加 try-catch,如下:

  widget _buildwidget() {
    try {
      return image(image: new cachednetworkimageprovider('test'));
    } catch (e) {
      print('enter catch exception start');
      print(e);
      print('enter catch exception end');
      return container();
    }
  }

依然没法捕获。

但是我们通过其自带的错误回调,如下:

  widget _buildwidget() {
    return image(
        image: new cachednetworkimageprovider(
            'test',
            errorlistener: () {
              print('enter errorlistener');
            }
        )
    );
  }

可以看到控制台进入了 errorlistener,打印了对应日志。

虽然 flutter 自带的错误日志依然输出了,但是通过 errorlistener 我们可以获得这种异常情况。

flutter: enter errorlistener
flutter: ══╡ exception caught by image resource service ╞════════════════════════════════════════════════════
flutter: the following message was thrown resolving an image codec:
flutter: couldn't download or retrieve file.

3.可访问非图片 url,比如 http://mp.weixin.qq.com/mp/homepage?__biz=mzi3otaynzawng==&hid=5&sn=7e4598d8b00537fe2846f2e85d746b9a&scene=18#wechat_redirect

  widget _buildwidget() {
    return image(
        image: new cachednetworkimageprovider(
            'http://mp.weixin.qq.com/mp/homepage?__biz=mzi3otaynzawng==&hid=5&sn=7e4598d8b00537fe2846f2e85d746b9a&scene=18#wechat_redirect',
            errorlistener: () {
              print('enter errorlistener');
            }
        )
    );
  }

运行,控制台会报错,并且没法捕获,控制台输出如下:

[verbose-2:codec.cc(97)] failed decoding image. data is either invalid, or it is encoded using an unsupported format.
flutter: ══╡ exception caught by image resource service ╞════════════════════════════════════════════════════
flutter: the following _exception was thrown resolving an image codec:
flutter: exception: operation failed

使用 try-catch 也是一样,这里就不赘余了。

图片通用异常捕获处理

通过上面的学习,我们可以发现不管是 image.network 还是 cached_network_image 没法覆盖全上面两种异常的捕获处理。

不过这两个的共同点就是他们都返回 image。

所以对于图片的异常捕获可以使用下面通用模板:

//    image image = image(image: new cachednetworkimageprovider(''));
image image = image.network('');
final imagestream stream = image.image.resolve(imageconfiguration.empty);
stream.addlistener((_, __) {}, onerror: (dynamic exception, stacktrace stacktrace) {
  //todo error callback
});

这里首先是获得 image,如果获得的是 imageprovider,只需要把 image.image 换为你的 imageprovider 即可,当然这个笔者没测试,只是看源码上面模板 image.image 的类型是 imageprovider。

addlistener 有两个回调,其中成功回调是必填的,有两个参数,因为这里不需要用到,因此第一个参数是一个下划线,第二个参数是两个下划线。可能你会说不需要用到,可不可以直接填 null。不行,这边测试了,填 null 当图片加载成功时控制台会抛异常。所以提供一个不需要任何实现的回调即可。

错误回调是可选的,因为我们本篇的主题就是要获取错误回调,所以这里提供了实现。

针对我们上面的 3 个例子,我们看看通用模板是否可以全部捕获。

1.一个图片的 url

widget _buildwidget() {
  image image = image.network('https://upload-images.jianshu.io/upload_images/5361063-e413832da0038304.png?imagemogr2/auto-orient/strip%7cimageview2/2/w/800');
  final imagestream stream = image.image.resolve(imageconfiguration.empty);
  stream.addlistener((_,__){}, onerror: (dynamic exception, stacktrace stacktrace) {
    print('enter onerror start');
    print(exception);
    print(stacktrace);
    print('enter onerror end');
  });
  return image;
}

图片加载成功。

2.不可访问 url,如随便一个字符串 test

widget _buildwidget() {
  image image = image.network('test');
  final imagestream stream = image.image.resolve(imageconfiguration.empty);
  stream.addlistener((_,__){}, onerror: (dynamic exception, stacktrace stacktrace) {
    print('enter onerror start');
    print(exception);
    print(stacktrace);
    print('enter onerror end');
  });
  return image;
}

控制台输出如下:

flutter: enter onerror start
flutter: invalid argument(s): no host specified in uri file:///test
flutter: #0      _httpclient._openurl (dart:_http/http_impl.dart:2121:9)
#1      _httpclient.geturl (dart:_http/http_impl.dart:2056:48)
#2      networkimage._loadasync (package:flutter/src/painting/image_provider.dart:486:57)
<asynchronous suspension>
#3      networkimage.load (package:flutter/src/painting/image_provider.dart:471:14)
#4      imageprovider.resolve.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:267:86)
#5      imagecache.putifabsent (package:flutter/src/painting/image_cache.dart:143:20)
#6      imageprovider.resolve.<anonymous closure> (package:flutter/src/painting/image_provider.dart:267:63)
#7      synchronousfuture.then (package:flutter/src/foundation/synchronous_future.dart:38:29)
#8      imageprovider.resolve (package:flutter/src/painting/image_provider.dart:265:30)
#9      myapp._buildwidget (package:my_flutter/main.dart:20:42)
#10     myapp.build (package:my_flutter/main.dart:12:18)
#11     statelesselement.build (package:flutter/<…>
flutter: enter onerror end

可以看到确实进入错误回调了。

3.可访问非图片 url,比如 http://mp.weixin.qq.com/mp/homepage?__biz=mzi3otaynzawng==&hid=5&sn=7e4598d8b00537fe2846f2e85d746b9a&scene=18#wechat_redirect

widget _buildwidget() {
  image image = image.network('http://mp.weixin.qq.com/mp/homepage?__biz=mzi3otaynzawng==&hid=5&sn=7e4598d8b00537fe2846f2e85d746b9a&scene=18#wechat_redirect');
  final imagestream stream = image.image.resolve(imageconfiguration.empty);
  stream.addlistener((_,__){}, onerror: (dynamic exception, stacktrace stacktrace) {
    print('enter onerror start');
    print(exception);
    print(stacktrace);
    print('enter onerror end');
  });
  return image;
}

控制台输出如下:

[verbose-2:codec.cc(97)] failed decoding image. data is either invalid, or it is encoded using an unsupported format.
flutter: enter onerror start
flutter: exception: operation failed
flutter: #0      networkimage._loadasync (package:flutter/src/painting/image_provider.dart:498:12)
<asynchronous suspension>
#1      networkimage.load (package:flutter/src/painting/image_provider.dart:471:14)
#2      imageprovider.resolve.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:267:86)
#3      imagecache.putifabsent (package:flutter/src/painting/image_cache.dart:143:20)
#4      imageprovider.resolve.<anonymous closure> (package:flutter/src/painting/image_provider.dart:267:63)
#5      synchronousfuture.then (package:flutter/src/foundation/synchronous_future.dart:38:29)
#6      imageprovider.resolve (package:flutter/src/painting/image_provider.dart:265:30)
#7      myapp._buildwidget (package:my_flutter/main.dart:20:42)
#8      myapp.build (package:my_flutter/main.dart:12:18)
#9      statelesselement.build (package:flutter/src/widgets/framework.dart:3774:28)
#10     componentelement.performrebuild (package:flutter/src/widgets/framework.dart:3721:15<…>
flutter: enter onerror end

可以看到确实进入错误回调了。

更多阅读:

flutter 入门系列博客
flutter & dart

最后来一个彩蛋表情包:

Flutter 异常处理之图片篇

Flutter 异常处理之图片篇