-2

如果网络/资产图像无法加载,我想要一种加载占位符图像的方法。这是我尝试过的。

class CircularImageWidget extends StatelessWidget {
  CircularImageWidget({
    Key key,
    @required this.radius,
    @required this.assetPath,
    @required this.imageType,
  }) : super(key: key);

  final double radius;
  final String assetPath;
  final ImageType imageType;

  Image getErrorImage() {
    return Image.asset(AssetUtils.profilepic);
  }

  ImageProvider returnImageAccordingToImageType() {
    if (imageType == ImageType.Network) {
      return NetworkImage(
        assetPath,
      );
    } else {
      return AssetImage(
        assetPath,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return CircleAvatar(
      backgroundImage: returnImageAccordingToImageType() ??
          AssetImage(AssetUtils.profilepic),
      radius: radius,
      onBackgroundImageError: (exception, stackTrace) {
        return AssetImage(AssetUtils.profilepic);
      },
    );
  }
}
4

1 回答 1

0

您可以通过检查图像的 URL 并基于它显示不同的小部件来实现这一点。

  @override
   Widget build(BuildContext context) {
   return CircleAvatar(
 imageURL== null? backgroundImage: 
      AssetImage(AssetUtils.profilepic),
  radius: radius,
 
):backgroundImage: 
      NetworkImage(imageURL),
  radius: radius,
 
),
}
于 2020-12-07T12:51:01.967 回答