flutter 图片加载失败导致布局出错的处理(debug环境
2021-11-20 本文已影响0人
小木虫666
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;
}
}