import 'package:flutter/material.dart';

class AsyncImage extends StatelessWidget {
  final String url;
  final double? width;

  const AsyncImage({
    super.key,
    required this.url,
    this.width,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: width,
      child: Image.network(
        url,
        fit: BoxFit.cover,
        // 加载中的样式
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) {
            return child; // 加载完成，直接返回图片
          }
          return Container(
            color: Colors.grey[200],
            alignment: Alignment.center,
            child: CircularProgressIndicator(strokeWidth: 2),
          );
        },
        // 加载失败的样式
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[200],
            child: const Icon(
              Icons.broken_image,
              size: 30,
              color: Colors.grey,
            ),
          );
        },
      ),
    );
  }
}
