美文网首页
flutter 图片加载失败导致布局出错的处理(debug环境

flutter 图片加载失败导致布局出错的处理(debug环境

作者: 小木虫666 | 来源:发表于2021-11-20 10:40 被阅读0次

Image这个Widget在加载网络图片的时候是可以监听加载过程的,直接上代码:

//封装图片加载控件,增加图片加载失败时加载默认图片
class CustomImageBuild extends StatefulWidget {
  final String url;
  final double w;
  final double h;
  final String defImagePath; // 默认是logo
  final BoxFit fit; // 默认是fill

  const CustomImageBuild(this.url, this.w, this.h,
      {this.defImagePath = "images/placeholder_image.png",
      this.fit = BoxFit.fill,
      Key key})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _StateCustomImageState();
  }
}

class _StateCustomImageState extends State<CustomImageBuild> {
  Image _image;

  @override
  void initState() {
    super.initState();
    _image = Image.network(
      widget.url,
      width: widget.w,
      height: widget.h,
    );
    var resolve = _image.image.resolve(ImageConfiguration.empty);
    resolve.addListener(
      ImageStreamListener(
        (_, __) {
          //加载成功
        },
        onError: (Object exception, StackTrace stackTrace) {
          //加载失败
          setState(
            () {
              _image = Image.asset(
                widget.defImagePath,
                width: widget.w,
                height: widget.h,
              );
            },
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _image;
  }
}


相关文章

网友评论

      本文标题:flutter 图片加载失败导致布局出错的处理(debug环境

      本文链接:https://www.haomeiwen.com/subject/kytetrtx.html