Caching data is extremely vital to have a performant app. Through caching, you avoid expensive operations when they are not needed. You for example fetch an image from the network only once and cache it locally. Thus you avoid the overhead as well as bandwith costs associated with re-downloading that resource.
This tutorial explores how to cache files using open source cache manager solutions. These are generic and can be used with any file.
(a). Use flutter_cache_manager
This is a CacheManager to download and cache files in the cache directory of the app.
Through this solution, various settings on how long to keep a file can be changed. It uses the cache-control http header to efficiently retrieve files.
Step 1: Install it
start by insatalling this solution. You do that by adding the dependency in your pubspec.yaml
as follows:
dependencies:
flutter_cache_manager: ^3.1.2
Then sync.
You can also install it via the terminal:
flutter pub add flutter_cache_manager
Step 2: Write Code
Start by importing the library:
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
Step 3: Write Code
For example to get a single file via the CacheManager
:
var file = await DefaultCacheManager().getSingleFile(url);
Here are more helpful functions:
getFileStream(url)
returns a stream with the first result being the cached file and later optionally the downloaded file.
getFileStream(url, withProgress: true)
when you set withProgress on true, this stream will also emit DownloadProgress when the file is not found in the cache.
downloadFile(url)
directly downloads from the web.
getFileFromCache
only retrieves from cache and returns no file when the file is not in the cache.
putFile
gives the option to put a new file into the cache without downloading it.
removeFile
removes a file from the cache.
emptyCache
removes all files from the cache.
Full Example
Here is a full example of how to use this plugin.
import 'package:baseflow_plugin_template/baseflow_plugin_template.dart';
import 'package:example/plugin_example/download_page.dart';
import 'package:example/plugin_example/floating_action_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
void main() {
runApp(BaseflowPluginExample(
pluginName: 'Flutter Cache Manager',
githubURL: 'https://github.com/Baseflow/flutter_cache_manager',
pubDevURL: 'https://pub.dev/packages/flutter_cache_manager',
pages: [CacheManagerPage.createPage()],
));
}
const url = 'https://blurha.sh/assets/images/img1.jpg';
/// Example [Widget] showing the functionalities of flutter_cache_manager
class CacheManagerPage extends StatefulWidget {
static ExamplePage createPage() {
return ExamplePage(Icons.save_alt, (context) => CacheManagerPage());
}
@override
_CacheManagerPageState createState() => _CacheManagerPageState();
}
class _CacheManagerPageState extends State<CacheManagerPage> {
Stream<FileResponse> fileStream;
void _downloadFile() {
setState(() {
fileStream = DefaultCacheManager().getFileStream(url, withProgress: true);
});
}
@override
Widget build(BuildContext context) {
if (fileStream == null) {
return Scaffold(
appBar: null,
body: const ListTile(
title: Text('Tap the floating action button to download.')),
floatingActionButton: Fab(
downloadFile: _downloadFile,
),
);
}
return DownloadPage(
fileStream: fileStream,
downloadFile: _downloadFile,
clearCache: _clearCache,
removeFile: _removeFile,
);
}
void _clearCache() {
DefaultCacheManager().emptyCache();
setState(() {
fileStream = null;
});
}
void _removeFile() {
DefaultCacheManager().removeFile(url).then((value) {
print('File removed');
}).onError((error, stackTrace) {
print(error);
});
setState(() {
fileStream = null;
});
}
}
Find the full code in the download links below.
Reference
Below are the reference links for this solution:
Number | Link |
---|---|
1. | Download code |
2. | Read More |