flutter/lib/components/network_or_asset_image.dart
2025-09-17 15:32:18 +08:00

53 lines
1.4 KiB
Dart

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class NetworkOrAssetImage extends StatelessWidget {
final String? imageUrl;
final double width;
final double? height;
final BoxFit fit;
final String placeholderAsset;
const NetworkOrAssetImage({
super.key,
required this.imageUrl,
this.width = 60.0,
this.height,
this.fit = BoxFit.cover,
this.placeholderAsset = 'assets/images/avatar/default.png',
});
@override
Widget build(BuildContext context) {
final isNetwork = imageUrl != null && imageUrl!.isNotEmpty && (imageUrl!.startsWith('http://') || imageUrl!.startsWith('https://'));
if (isNetwork) {
return CachedNetworkImage(
imageUrl: imageUrl!,
width: width,
height: height,
fit: fit,
placeholder: (context, url) => Image.asset(
placeholderAsset.isEmpty ? 'assets/images/avatar/default.png' : placeholderAsset,
width: width,
height: height,
fit: fit,
),
errorWidget: (context, url, error) => Image.asset(
placeholderAsset,
width: width,
height: height,
fit: fit,
),
);
} else {
return Image.asset(
(imageUrl != null && imageUrl!.isNotEmpty) ? imageUrl! : placeholderAsset,
width: width,
height: height,
fit: fit,
);
}
}
}