Cache Manager with Flutter

Veli Bacık
Jul 27, 2020 · 6 min read

Cache management is essential for a mobile app, so if you write your package, power is with for you.

Cache keyword is simply stored data. Cache term has every language or framework. You need to know ”where and when need“ so need sometimes device has not connected the internet or sometimes writing the file and document library.

We use two platforms for caching:

  • Shared Preferences (Key-Value little database on mobile)
  • File (Any .json file on a mobile device)

And we need these core features:

  • Get Data
  • Write Data
  • Remove Data

We think now. Will do core features code every platform it every time? Yes of course because of the different environment every platform. If platform kind increases may fall code quality so we need some patterns to manage this problem.

Strategy Pattern

We have many platforms so need a guider every platform. This guide should be cache algorithms and must contain this guide platforms to use.

Any file operation class needs this interface, so their properties become standard.

WriteUserRequestDataWithTime: It’s writing data on cache. When key and date came, this is going to write data by time. If it passes the writing process successfully, will return the true value or has any problem return the false.

GetUserRequestDataOnString: These function return the caching data for key value.

RemoveUserRequestSingleCache: This time, remove model by the key on a cache.

RemoveUserRequestCache: Finally, remove all cache. (Why need a key? We will soon 🤗 hint: safety 🤫)

Cache on Shared Preferences

We most know that package if recently use flutter. It’s pretty easy to save on cache but this package only works primitive types. We added a dynamic model caching with the use of JSON encode and decode.

Primitive types like int, double, string etc…
Dynamic model like User, Student, List<Location> …

Caching need always while app using and doesn’t modify any time so crated singleton instance for name local manager.

Okay, we have cache manager instance but don’t forget, it is own manager so does not preference instance. Preferences instance need future(sync) to init but if load the value first time, don’t need load each time.

We added preferences instance so initialize only once.

Let’s write a dynamic model to preferences. User must be declared duration for know “How long will it remain?”. We need a unique key for caching model so need to URL(key). BaseLocal is our caching model.

We check preferences then check duration. We create a base local model. This model has a body model and a new duration time (current time + duration). After created model, model converted to JSON for caching. Now, we used the set string method for storing model.

Okay, we kept the dynamic model preferences store with duration. Now, we need to see this model. Let’s write to get model function.

Firstly, take your model string for the key(URL) and if this JSON does not empty, we will convert JSON to BaseLocal model so model duration time very important. We control now with model time. If model time bigger now, return this model otherwise remove the old model and back to null.

We can write any model or get any model on the cache now. Finally, need to remove on the cache. We need to remove a single model or all model.

Flutter doesn’t support multi-context architecture. If you use preferences clear method all data remove so you remove user own data. That’s why we can’t use this method. We used to remove manually method.

Finally, let’s look shared manager class.

Shared Manager extend IFileManager
Preferences case complete.

Cache on File

We know what to do because created strategy design. Now, just create a file manager class and implement the File Manager interface.

  • We will create a single instance to file manager again.
  • We must be given a file name when class occurs.
final String fileName = "fireball.json";

I did it “.json” on purpose because will keep JSON file in the device.

If you want file operation, you need a route path.

Application Directory Path: User doesn’t see this directory so doesn’t any operation. It does not need any permission.

Temporary Directory Path: User can see this directory and may change file but don't forgot, you should get write-read directory permission for external operations.

Android Data Permission Apple Data Permission

We prefer application path so doesn’t need any permission. Let’s write the route path code.

Now, we have a document path in the application. We will use this path for the file operation.

Read all data to JSON file then file source convert to map object. We have a map object so use key to get any model.

We can use the map object and retrieve all data.

Retrieve Data For Key

A user sends to key and we check the model for a key. If have any model, convert to base local model and check the model time. When The model time is bigger now, returned the model otherwise remove data on the file and returned empty data.

Let’s write any model on the local file.

Firstly, we load to file and user model convert to JSON. We create a map object for user key and value. It’s ready to write a file. Finally, create local file instance and write user model in the file.

We use flush mode right, and file mode write. It all data remove then write a new map object on the file every request. (This solution for new map object write to file.)

Now, remove the data single and all history.

We’re looking key on a local file. If found the key, remove data on a map. After removing the model, wrote renewed data on the file.

Finally, it’s very easy to clean the file. We just remove the directory and everything data removed.

Let’s look at the file manager model in the last situation.

We have core architecture for caching. Let’s use on the real app.

Firstly, I create a network manager class and define IFileManager object. It has custom get method and if has valid cache data, doesn’t need to send any request. (This case to reduce API consume)

And little view for caching 🤗

We looked at the screen and saw a result.

Everything it’s okay ☘️ We ready use for cache architecture.

Thank you, may the beauty be with you.
See you in new articles 🙋‍♂️

Flutter Community

Articles and Stories from the Flutter Community