Tuesday, June 18, 2024
Google search engine
HomeToolsCache Management in Flutter

Cache Management in Flutter

Managing the cache memory and fetching the data faster

Introduction

Cache memory is a faster memory storage that stores the data in the memory of the phone locally. It stores the data for a fixed period of time after its data is being cleaned form the memory. We can also use local database techniques such as moor database, SQLite database to store the data but some packages provide us simple methods and functionality to implement cache memory with your app.

In this blog, we will learn how to use cache memory to store the app data, fetch data when needed, delete the data from the memory, delete the entire cache data of the app. Let’s do it…

Demo::


Table of content

  1. Installing dependency
  2. Upload Data in Cache Memory
  3. Fetch data from Cache Memory
  4. Empty cache
  5. Understanding other methods
  6. Github Link

Installing dependency

flutter_cache_manager provides us various methods to perform various operations.

flutter_cache_manager | Flutter Package
A CacheManager to download and cache files in the cache directory of the app. Various settings on how long to keep a…pub.dev

Upload Data in Cache Memory

Initializing file stream

Stream<FileResponse> fileStream = DefaultCacheManager().getFileStream(url);

DefaultCacheManager class provides us getFileStream method to get the stream of the file, it takes the URL to and upload the file inside the cache memory of the device.fileStream returns the stream of FileResponse that stores the information about the file such as file location, time of validity, original URL of the file, source of the file, and file.

Creating a StatelessWidget that returns the stream of FileResponse to display the file

class UploadCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("UploadCacheMemoryData");
return StreamBuilder<FileResponse>(
stream: fileStream,
builder: (_, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Type:${fileInfo.runtimeType}"),
],
)
: Center(
child: Text("Uploading..."),
);
},
);
}
}
  1. This class returns the stream of FileResponce , builder takes context, and snapshot .snapshot is used to access the file information.
  2. FileInfo fileInfo = snapshot.data as FileInfo; here snapshot data is used FileInfo so that we can access the various methods that provide us information.
  3. For UI we are just displaying the uploaded file on the screen toFileInfo.file provides us the address of the file, to display the file image Image.file() widget is used.

Fetch data from Cache Memory

Initializing the Future

Future<FileInfo> fileInfoFuture = DefaultCacheManager().getFileFromCache(url);

DefaultCacheManager provide us getFileFromCache method to provides the file from the cache memory with the specific URL.

Creating a StatelessWidget that returns the FutureBuilderof FileInfo

DefaultCacheManager().getFileFromCache(url) returns a future that is why we require a FutureBuilder to control fileInfoFuture , the UI part is the same as above.

class FetchCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("FetchCacheMemoryData");
return FutureBuilder(
future: fileInfoFuture,
builder: (context, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Hash code:${fileInfo.runtimeType}"),
],
)
: Center(child: Text("Fetching..."));
},
);
}
}

Empty cache

DefaultCacheManager provides us emptyCache method delete the entire app cache. In this particular example, we are also setting fileInfoFuture to null . (For better understanding refer full code)

onPressed: () {
DefaultCacheManager().emptyCache();
setState(() {
fileInfoFuture = null;
});
},

Understanding other methods

Refer Usage section

flutter_cache_manager | Flutter Package
A CacheManager to download and cache files in the cache directory of the app. Various settings on how long to keep a…pub.dev

Full code

import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: [
FlatButton(
onPressed: () {
DefaultCacheManager().emptyCache();
setState(() {
fileInfoFuture = null;
});
},
child: Text("Clear cache"))
],
title: Text("Cache memory demo"),
),
body: fileInfoFuture == null
? UploadCacheMemoryData()
: FetchCacheMemoryData()),
);
}
}

class UploadCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("UploadCacheMemoryData");
return StreamBuilder<FileResponse>(
stream: fileStream,
builder: (_, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Hash code:${fileInfo.runtimeType}"),
],
)
: Center(
child: Text("Uploading..."),
);
},
);
}
}

class FetchCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("FetchCacheMemoryData");
return FutureBuilder(
future: fileInfoFuture,
builder: (context, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Hash code:${fileInfo.runtimeType}"),
],
)
: Center(child: Text("Fetching..."));
},
);
}
}

Stream<FileResponse> fileStream = DefaultCacheManager().getFileStream(url);
Future<FileInfo> fileInfoFuture = DefaultCacheManager().getFileFromCache(url);
const url = 'https://avatars1.githubusercontent.com/u/41328571?s=280&v=4';

Github Link

flutter-devs/cache_management_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


If you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments