import 'dart:async'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image_platform_interface/cached_network_image_platform_interface.dart'; import 'package:flutter/material.dart'; import 'package:music_web_player/api.dart'; import 'package:music_web_player/config.dart'; class CoverImage extends StatefulWidget { final MusicEntry music; final double? width; final double? height; final BoxFit? fit; final Icon? icon; final Color? backgroundColor; final Duration? delayLoading; const CoverImage({ Key? key, required this.music, this.width, this.height, this.icon, this.fit, this.backgroundColor, this.delayLoading, }) : super(key: key); @override State createState() => _CoverImageState(); } class _CoverImageState extends State { var _canShowImage = true; Timer? _timer; @override void initState() { super.initState(); if (widget.delayLoading != null) { _canShowImage = false; Timer(widget.delayLoading!, () { if (mounted) { setState(() => _canShowImage = true); } }); } } @override void dispose() { super.dispose(); _timer?.cancel(); } @override Widget build(BuildContext context) { if (!_canShowImage) return _loadingWidget(null); return CachedNetworkImage( width: widget.width, height: widget.height, imageRenderMethodForWeb: ImageRenderMethodForWeb.HttpGet, imageUrl: widget.music.coverURL, cacheKey: widget.music.coverCacheKey, httpHeaders: {"Token": config.apiToken}, useOldImageOnUrlChange: false, progressIndicatorBuilder: (c, s, p) => _loadingWidget(p.progress), fit: widget.fit, errorWidget: (c, s, e) => _loadingWidget(null), ); } Widget _loadingWidget(double? progress) => Container( color: widget.backgroundColor ?? Colors.black, width: widget.width, height: widget.height, child: Center( child: progress == null ? widget.icon : CircularProgressIndicator(value: progress), ), ); }