AssetKamKaro: Flutter Asset Optimization Guide
AssetKamKaro: Flutter Asset Optimization Guide
AssetKamKaro is a powerful Flutter package designed to help developers optimize their app's assets, reducing app size while maintaining quality. This comprehensive guide will walk you through everything you need to know to get the most out of AssetKamKaro.
Installation
Adding to Your Project
Add AssetKamKaro to your pubspec.yaml
:
dependencies:
assetkamkaro: ^0.1.1
Run the following command to install:
flutter pub get
Configuration
Basic Setup
Create a config.yaml
file in your project root:
# AssetKamKaro Configuration
compression:
level: high # Options: low, medium, high
jpeg:
quality: 80 # 0-100
subsampling: yuv420
png:
level: 9 # 0-9
filter: 0
# Directories to exclude from optimization
exclude:
- assets/icons
- assets/backgrounds
- assets/raw
# Backup settings
backup: true
delete_unused: false
# Performance settings
enable_cache: true
parallel_processing: true
Core Features
1. Asset Optimization
import 'package:assetkamkaro/assetkamkaro.dart';
void optimizeAssets() async {
// Initialize the optimizer
final optimizer = AssetKamKaro(
enableCache: true,
);
try {
// Run optimization
final result = await optimizer.optimize(
projectPath: Directory.current.path,
compressionLevel: CompressionLevel.high,
dryRun: false,
createBackup: true,
excludePatterns: ['assets/icons', 'assets/raw'],
);
// Process results
print('Optimization Results:');
print('- Total assets processed: ${result.totalAssetsProcessed}');
print('- Total size reduction: ${(result.totalSizeReduction / 1024).toStringAsFixed(2)} KB');
// Handle unused assets
if (result.unusedAssets.isNotEmpty) {
print('\nUnused Assets Found:');
for (final asset in result.unusedAssets) {
print('- $asset');
}
}
// Detailed compression results
print('\nCompression Details:');
result.compressionResults.forEach((path, details) {
print('$path:');
print(' - Original: ${(details.originalSize / 1024).toStringAsFixed(2)} KB');
print(' - Compressed: ${(details.compressedSize / 1024).toStringAsFixed(2)} KB');
print(' - Reduction: ${details.reduction.toStringAsFixed(2)}%');
});
} catch (e) {
print('Optimization failed: $e');
}
}
2. Command Line Interface
AssetKamKaro provides a powerful CLI for automation and CI/CD integration:
# Basic optimization
dart run assetkamkaro optimize
# High compression with specific settings
dart run assetkamkaro optimize \
--compression high \
--exclude assets/icons,assets/backgrounds \
--backup true
# Dry run for analysis
dart run assetkamkaro optimize --dry-run
# Delete unused assets
dart run assetkamkaro optimize --delete-unused
# Custom configuration file
dart run assetkamkaro optimize --config custom_config.yaml
Advanced Usage
Pre-release Optimization Pipeline
void preReleaseOptimization() async {
final optimizer = AssetKamKaro();
// 1. Analyze current state
final analysis = await optimizer.analyzeAssets(
projectPath: Directory.current.path,
);
// 2. Create backup
await optimizer.createBackup(
projectPath: Directory.current.path,
backupPath: 'backups/pre_release_${DateTime.now().toIso8601String()}',
);
// 3. Optimize assets
final result = await optimizer.optimize(
projectPath: Directory.current.path,
compressionLevel: CompressionLevel.high,
createBackup: true,
);
// 4. Generate report
await optimizer.generateReport(
result: result,
outputPath: 'reports/optimization_report.html',
);
}
Selective Asset Processing
void processSpecificAssets() async {
final optimizer = AssetKamKaro();
// Process only images in specific directories
await optimizer.optimize(
projectPath: Directory.current.path,
includePatterns: ['assets/images/**/*.png', 'assets/images/**/*.jpg'],
compressionLevel: CompressionLevel.medium,
);
// Process with different settings for different types
await optimizer.optimize(
projectPath: Directory.current.path,
compressionSettings: {
'png': CompressionSettings(level: 9),
'jpg': CompressionSettings(quality: 85),
},
);
}
Best Practices
1. Asset Organization
// Recommended asset structure
assets/
├── images/
│ ├── icons/ # Small UI elements
│ ├── backgrounds/ # Background images
│ └── content/ # Content images
├── fonts/
└── raw/ # Original, unoptimized assets
2. Optimization Strategy
void optimizationStrategy() async {
final optimizer = AssetKamKaro();
// 1. Initial analysis
final analysis = await optimizer.analyzeAssets(
projectPath: Directory.current.path,
);
// 2. Process different asset types with appropriate settings
await optimizer.optimize(
projectPath: Directory.current.path,
compressionSettings: {
'icons': CompressionSettings(level: 9), // Maximum compression for icons
'backgrounds': CompressionSettings(quality: 85), // High quality for backgrounds
'content': CompressionSettings(quality: 80), // Balanced for content
},
);
// 3. Clean up unused assets
if (analysis.unusedAssets.isNotEmpty) {
await optimizer.deleteUnusedAssets(
assets: analysis.unusedAssets,
backup: true,
);
}
}
Troubleshooting
Common Issues and Solutions
-
Optimization Failed
try { await optimizer.optimize(...); } catch (e) { // Check file permissions if (e is FileSystemException) { print('Permission error: ${e.message}'); } // Check disk space if (e is IOException) { print('Disk space error: ${e.message}'); } }
-
No Size Reduction
// Verify compression settings final result = await optimizer.optimize( compressionLevel: CompressionLevel.high, verifyResults: true, // Enable detailed verification );
-
Performance Issues
// Adjust processing parameters await optimizer.optimize( batchSize: 25, // Reduce batch size parallelProcessing: false, // Disable parallel processing cacheEnabled: true, // Enable caching );
CI/CD Integration
GitHub Actions Example
name: Asset Optimization
on:
push:
branches: [ main ]
jobs:
optimize:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Flutter
uses: subosito/flutter-action@v1
with:
flutter-version: '3.x'
- name: Install Dependencies
run: flutter pub get
- name: Optimize Assets
run: dart run assetkamkaro optimize --compression high --backup true
- name: Commit Changes
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add .
git commit -m "Optimize assets"
git push
Conclusion
AssetKamKaro provides a comprehensive solution for optimizing your Flutter app's assets. By following this guide and implementing the best practices, you can significantly reduce your app size while maintaining quality.
Remember to:
- Always create backups before optimization
- Use appropriate compression levels for different asset types
- Monitor optimization results
- Integrate optimization into your development workflow
Happy optimizing! 🚀