Caching Text API data with Flutter

Hrishikesh Deshmukh
3 min readJul 4, 2020

A glimpse on caching TEXT data in flutter.

Hola Amigos! I hope the lock-down is proving to be a productive one for y’all !

So, the other day I got a chance to work on an application that had a requirement to store data in app’s cache and load the data from cache, next time the app loads up.

I started learning flutter directly and had no native experience, so had no clue on how to store text data in to the cache. I had a hard time finding tutorials on the topic. However, there are a lot of tutorial videos on storing the images into the cache but not on storing text data. So this post is dedicated to all the developers who are First Timers(probably noobs) like me!

Lets get coding!!

We will be using Reqres API’s getUsers endpoint to get our data.

Step 1- Creating a model class for API Response from our favorite tool — Quicktype

Step 2- Import the packages:

We need the following packages to make our task possible:

  1. http: To make API calls through internet
  2. path_provider: To retrieve the path to the Cache directory.

Step 3- Making the API call and Storing the data to Cache

In this step, we get access to the cache directory by calling getTemporaryDirectory() method from path_provider.

Then, check if the json File exists in the directory or not, by calling exists() mehtod from dart:io on the File like so:

If Cache file Exists …

  1. Read the JSON File
  2. transform the content into ApiResponse model
  3. return the ApiResponse model.

If cache is Empty…

  1. Make the API call and transform the API response body into the ApiResponse model.
  2. Open the File in write mode and save the response body to the file.
  3. return the ApiResponse model generated in first step.

Step 4- Code the UI

We shall use the basic boiler template in main.dart and modifying the body property of Scaffold.

main.dart

Step 5- Run the App to see the magic!!

We can see that the app Loads the data from API for the First Time. Now hot reload the app, we see in our logs, that the Data is being loaded from the Cache.

Optional Method- We can delete the cache file, hot reload to see the changes:

Create a Fab Button in the Scaffold as shown and call a function _deleteCacheContents() to clear the cache like so:

Now, simply hot reload your app to cross verify the results!!

+

You can find the complete GitHub project here

https://github.com/hrishikeshd10/flutter_caching

If you have liked this post, go ahead and give it a clap, share it with your friends. For more posts, please hit the subscribe button. For any suggestions or questions please let me know in the comments section. Until next time…#StayHome #StaySafe #HappyLearning and #HappyCoding !!!

--

--