flutter_cached_svg 1.0.1

SDKflutter
Platformandroidioswindowslinuxmacosweb

A high-performance Flutter package for loading and caching SVG images from network URLs with full cross-platform support, including Flutter Web.

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.

pub package License: MIT Flutter

✨ 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

PlatformSupportImplementation
AndroidFile-based caching via flutter_cache_manager
iOSFile-based caching via flutter_cache_manager
WeblocalStorage caching with HTTP requests
DesktopFile-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

ParameterTypeDescriptionDefault
urlStringThe SVG image URLRequired
widthdouble?Image widthnull
heightdouble?Image heightnull
placeholderWidget?Widget shown while loadingnull
errorWidgetWidget?Widget shown on errornull
colorFilterColorFilter?Color filter to applynull
fitBoxFitHow the image should fitBoxFit.contain
alignmentAlignmentGeometryImage alignmentAlignment.center
fadeDurationDurationFade-in animation duration300ms
cacheKeyString?Custom cache keyAuto-generated
headersMap<String, String>?HTTP headersnull
cacheManagerBaseCacheManager?Custom cache managerDefaultCacheManager()

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://raw.githubusercontent.com/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

  1. Pre-cache important images during app initialization
  2. Use appropriate image sizes to reduce bandwidth
  3. Implement custom cache managers for fine-tuned control
  4. Clear cache periodically to manage storage space
  5. 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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for your changes
  5. Ensure all tests pass (flutter test)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

📞 Support


Made with ❤️ by Your Name