getImageWidget static method

Widget getImageWidget(
  1. String imagePath, {
  2. double? width,
  3. double? height,
  4. bool inRongCloud = true,
  5. Color? color,
  6. BoxFit fit = BoxFit.cover,
  7. String? thumbnailBase64String,
  8. bool notInAssets = false,
})

获取图片 Widget,可以自动判断图片路径类型

Implementation

static Widget getImageWidget(
  String imagePath, {
  double? width,
  double? height,
  bool inRongCloud = true,
  Color? color,
  BoxFit fit = BoxFit.cover,
  String? thumbnailBase64String,
  bool notInAssets = false,
}) {
  if (thumbnailBase64String != null && thumbnailBase64String.isNotEmpty) {
    try {
      // 使用缓存机制解码base64数据
      Uint8List? bytes = getDecodedBase64(thumbnailBase64String);

      if (bytes == null) {
        return SizedBox(width: width, height: height);
      }

      return Image.memory(
        bytes,
        width: width,
        height: height,
        fit: fit,
        color: color,
        errorBuilder: (context, error, stackTrace) {
          return SizedBox(width: width, height: height);
        },
      );
    } catch (e) {
      return SizedBox(width: width, height: height);
    }
  }

  if (imagePath.isEmpty) {
    return SizedBox(width: width, height: height);
  }
  // 判断图片路径是否为网络地址
  bool isNetworkImage =
      imagePath.startsWith('http://') || imagePath.startsWith('https://');

  double circularSize =
      (width ?? 20) > (height ?? 20) ? (width ?? 20) / 2 : (height ?? 20) / 2;

  if (isNetworkImage) {
    // 使用 CachedNetworkImage 显示网络图片
    return CachedNetworkImage(
      imageUrl: imagePath,
      width: width,
      height: height,
      fit: fit,
      placeholder: (context, url) => Center(
          child: SizedBox(
              width: circularSize,
              height: circularSize,
              child: CircularProgressIndicator(strokeWidth: 2))), // 加载中的占位符
      errorWidget: (context, url, error) =>
          const Icon(Icons.error), // 加载失败的占位符
      color: color,
    );
  } else {
    // 本地资源图片,判断是否已经有 "assets/" 前缀
    if (notInAssets) {
      // 在 Web 平台上,不支持本地文件访问,显示错误图标
      if (kIsWeb) {
        return Icon(
          Icons.error,
          size: width ?? height ?? 24,
          color: color ?? Colors.grey,
        );
      } else {
        return Image.file(
          File(imagePath),
          width: width,
          height: height,
          fit: fit,
          color: color,
          errorBuilder: (context, error, stackTrace) {
            return SizedBox(width: width, height: height);
          },
        );
      }
    } else {
      String assetPath =
          imagePath.startsWith('assets/') ? imagePath : 'assets/$imagePath';

      return Image.asset(
        assetPath,
        width: width,
        height: height,
        fit: fit,
        color: color,
        package: inRongCloud ? 'rongcloud_im_kit' : null,
      );
    }
  }
}