flutter_cached_svg
A high-performance Flutter package for loading and caching SVG images from network URLs with full cross-platform support, including Flutter Web.
β¨ Features
- π Cross-platform support: Works on Mobile, Desktop, and Web
- π¦ Smart caching: Automatic caching with customizable cache management
- π¨ Customizable: Full control over placeholders, error widgets, and styling
- β‘ Performance: Optimized loading with fade animations
- π Web-first: Built with Flutter Web compatibility in mind
- π§ Easy to use: Drop-in replacement for network SVG loading
ποΈ Platform Support
Platform | Support | Implementation |
---|---|---|
Android | β | File-based caching via flutter_cache_manager |
iOS | β | File-based caching via flutter_cache_manager |
Web | β | localStorage caching with HTTP requests |
Desktop | β | File-based caching via flutter_cache_manager |
π± Installation
Add this to your package's pubspec.yaml
file:
dependencies:
flutter_cached_svg: ^1.0.0
Then run:
flutter pub get
π Quick Start
Basic Usage
import 'package:flutter_cached_svg/flutter_cached_svg.dart';
FlutterCachedSvg(
'https://example.com/image.svg',
width: 100,
height: 100,
)
With Customization
FlutterCachedSvg(
'https://example.com/image.svg',
width: 200,
height: 200,
placeholder: const CircularProgressIndicator(),
errorWidget: const Icon(Icons.error, color: Colors.red),
colorFilter: const ColorFilter.mode(Colors.blue, BlendMode.srcIn),
fadeDuration: const Duration(milliseconds: 500),
)
Cache Management
// Pre-cache an image
await FlutterCachedSvg.preCache('https://example.com/image.svg');
// Clear cache for specific URL
await FlutterCachedSvg.clearCacheForUrl('https://example.com/image.svg');
// Clear all cache
await FlutterCachedSvg.clearCache();
π API Reference
FlutterCachedSvg
Parameter | Type | Description | Default |
---|---|---|---|
url |
String |
The SVG image URL | Required |
width |
double? |
Image width | null |
height |
double? |
Image height | null |
placeholder |
Widget? |
Widget shown while loading | null |
errorWidget |
Widget? |
Widget shown on error | null |
colorFilter |
ColorFilter? |
Color filter to apply | null |
fit |
BoxFit |
How the image should fit | BoxFit.contain |
alignment |
AlignmentGeometry |
Image alignment | Alignment.center |
fadeDuration |
Duration |
Fade-in animation duration | 300ms |
cacheKey |
String? |
Custom cache key | Auto-generated |
headers |
Map<String, String>? |
HTTP headers | null |
cacheManager |
BaseCacheManager? |
Custom cache manager | DefaultCacheManager() |
Static Methods
// Pre-cache an image
static Future<void> preCache(String imageUrl, {
String? cacheKey,
BaseCacheManager? cacheManager,
})
// Clear cache for specific URL
static Future<void> clearCacheForUrl(String imageUrl, {
String? cacheKey,
BaseCacheManager? cacheManager,
})
// Clear all cache
static Future<void> clearCache({BaseCacheManager? cacheManager})
π‘ Examples
Loading with Custom Placeholder
FlutterCachedSvg(
'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/flutter.svg',
width: 80,
height: 80,
placeholder: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.image, color: Colors.grey),
),
)
Applying Color Filters
FlutterCachedSvg(
'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/github.svg',
width: 50,
height: 50,
colorFilter: const ColorFilter.mode(
Colors.blueAccent,
BlendMode.srcIn,
),
)
Grid of Cached SVGs
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: svgUrls.length,
itemBuilder: (context, index) {
return FlutterCachedSvg(
svgUrls[index],
placeholder: const CircularProgressIndicator(),
errorWidget: const Icon(Icons.broken_image),
);
},
)
Pre-caching Multiple Images
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final List<String> svgUrls = [
'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/react.svg',
'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/flutter.svg',
// ... more URLs
];
@override
void initState() {
super.initState();
_preCacheImages();
}
Future<void> _preCacheImages() async {
for (String url in svgUrls) {
await FlutterCachedSvg.preCache(url);
}
}
@override
Widget build(BuildContext context) {
// Your app content
}
}
π Web-Specific Considerations
CORS-Free SVG Sources
For Flutter Web, use CORS-enabled SVG sources:
// β
CORS-free sources
static const List<String> webFriendlySvgs = [
'https://rawgit.flutter-io.cn/twitter/twemoji/master/assets/svg/1f60a.svg',
'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/flutter.svg',
'https://cdn.jsdelivr.net/npm/feather-icons@4.29.0/dist/icons/heart.svg',
];
Web Caching
On web platforms, the package uses localStorage
for caching instead of file system:
- Cache is persistent across browser sessions
- Automatically manages storage space
- Falls back gracefully if localStorage is unavailable
π§ Advanced Configuration
Custom Cache Manager
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
final customCacheManager = CacheManager(
Config(
'customSvgCache',
stalePeriod: const Duration(days: 7),
maxNrOfCacheObjects: 100,
),
);
FlutterCachedSvg(
'https://example.com/image.svg',
cacheManager: customCacheManager,
)
Custom Headers
FlutterCachedSvg(
'https://api.example.com/protected-svg',
headers: {
'Authorization': 'Bearer your-token',
'User-Agent': 'MyApp/1.0',
},
)
π¨ Styling Options
Different Fit Modes
// Contain (default)
FlutterCachedSvg(url, fit: BoxFit.contain)
// Cover
FlutterCachedSvg(url, fit: BoxFit.cover)
// Fill
FlutterCachedSvg(url, fit: BoxFit.fill)
// Scale down
FlutterCachedSvg(url, fit: BoxFit.scaleDown)
Alignment Options
FlutterCachedSvg(
url,
alignment: Alignment.topLeft, // Top-left
alignment: Alignment.center, // Center (default)
alignment: Alignment.bottomRight, // Bottom-right
)
π¨ Error Handling
FlutterCachedSvg(
'https://invalid-url.svg',
errorWidget: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.red[100],
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.red),
),
child: const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.broken_image, color: Colors.red, size: 32),
SizedBox(height: 8),
Text('Failed to load SVG', style: TextStyle(color: Colors.red)),
],
),
),
)
π Migration Guide
From cached_network_svg_image
// After
FlutterCachedSvg(
'https://example.com/image.svg',
colorFilter: const ColorFilter.mode(Colors.blue, BlendMode.srcIn), // β
New way
)
π Performance Tips
- Pre-cache important images during app initialization
- Use appropriate image sizes to reduce bandwidth
- Implement custom cache managers for fine-tuned control
- Clear cache periodically to manage storage space
- Use placeholders to improve perceived performance
π Troubleshooting
Common Issues
CORS errors on web:
- Use CORS-enabled SVG sources (see Web-Specific Considerations)
- Consider hosting SVGs on your own CDN
Images not caching:
- Check if URLs are accessible
- Verify cache manager configuration
- Clear cache and retry
Performance issues:
- Reduce image sizes
- Implement lazy loading
- Use appropriate cache strategies
Debug Mode
Enable logging to debug caching issues:
import 'dart:developer';
// The package automatically logs errors in debug mode
// Check your console for detailed error messages
π€ Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
flutter test
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Acknowledgments
- Built on top of flutter_svg
- Uses flutter_cache_manager for mobile/desktop caching
- Inspired by the need for better SVG caching on Flutter Web
π Support
- π§ Email:
your-email@example.com
- π Issues: GitHub Issues
- π¬ Discussions: GitHub Discussions
Made with β€οΈ by Your Name