Flutter Image 图片类及加载异常的处理

图片的格式 一定要注意,该有缩进的一定要有缩进,要带上横线,上下保持一致,路径要对。

Image

图片透明度的显示:

Image.network(
  'https://raw.githubusercontent.com/flutter/assets-for-api-docs/master/packages/diagrams/assets/blend_mode_destination.jpeg',
  color: Color.fromRGBO(255, 255, 255, 0.5),
  colorBlendMode: BlendMode.modulate
)

多个图片的布局

https://flutter.cn/docs/development/ui/layout

NetworkImageWithRetry

Use NetworkImageWithRetry instead of Image.network to load images from the network with a retry mechanism.

Example:

var avatar = new Image(
  image: new NetworkImageWithRetry('http://example.com/avatars/123.jpg'),
);

The retry mechanism may be customized by supplying a custom FetchStrategy function. FetchStrategyBuilder is a utility class that helps building fetch strategy functions.

 

在图片还没有加载进来时,可以用进度条进行替换

child: Image.network(
          "https://2a.zol-img.com.cn/product/124_501x2000/746/cexItD2yJ21Rs.jpg",
          loadingBuilder: (context, child, loadingProgress) {
            return loadingProgress == null ? child : LinearProgressIndicator();
          },
        ),

另外,如果没有这个图片,下面的封装类可以对异常进行处理。

import 'package:flutter/material.dart';

//封装图片加载控件,增加图片加载失败时加载默认图片
class ImageWidget extends StatefulWidget {
  ImageWidget(
      {required this.url,
      required this.w,
      required this.h,
      this.defImagePath = "assets/images/ic_launcher_round.png"});

  final String url;
  final double w;
  final double h;
  final String defImagePath;

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

class _StateImageWidget extends State<ImageWidget> {
  late 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;
  }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

computerclass

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值