Exploring Data storing methods locally in Flutter

CodeStax.Ai
8 min readSep 27, 2023

--

Every application we use has to store data either internally or externally for functionality of the application. It would be tedious if you prompt for user data every time. Yet the importance of storing data lies in where it is getting stored. Application data are getting stored in the Device or internal storage has always an upper hand over external storage methods that is through cloud because of no confidential data leak possible, no data latency, doesn’t require internet to fetch data and so on. Of course, when your data requirements for the application is quite high or want to maintain real-time data on an ease, then external storage via cloud is most preferable.

Flutter offers cross-platform support to both internal and external storage methods to persist data. Thanks to the open source community, now numerous powerful plugins are coming up for data persistence in flutter. Here in this article, data storing techniques in device or locally in a flutter applications are going to be discussed.

Before actually persist data onto a device, it is important to know the persistence layer of an application. Because that’s where data encoding, storing, retrieving handlers are defined.

PERSISTENCE LAYER

The persistence layer is a centralized layer within an application that receives all data calls from the business layer and handles the request by accessing the storage of the application.

It contains the essential logic which is responsible for creating, reading, updating, and deleting persistent objects using the cache, queries and expressions, as well as transactions by accessing the database. The main purpose of using persistence layer is to isolate the read/write/delete logic from the business layer. When any changes made in business layer of saving data for an application, only the persistence layer logic would change Not the whole code.

Photo by O’reilly

TYPES OF LOCAL DATA PERSISTENCE IN FLUTTER

Once the data are serialized, saving as a variable in memory is not persistence. When application gets restarted, data are gone. By saving in a disk lets you load the data again after a restart. Flutter offers several way to store data locally. Yet the very popular and native framework data storing methods are discussed here

1. Shared Preferences

2. Through Files

3. SQLite

1. Shared preferences

Shared preferences is a flutter plugin used to store small collection of Data predominantly key-value pairs on the Disk. Eg: Cached page index, Color theme, authentication tokens. The shared preferences plugin wraps NSUserDefaults on iOS and sharedPreferences on Android, thereby providing a single plugin for cross platform usage.

  • Add the dependency

To add shared_preferences package as dependency, run flutter pub add:

$ flutter pub add shared_preferences
  • Write data

Shared Preferences package provides Setter methods to persist data locally. Setter methods are available for primitive types such as Int, Bool, String, StringList.

Setter methods do two things: first synchronously update the key-value pair and persist them to disk.

Here variable ‘counter’ is getting stored with the key ‘counter’ through setInt() method provided by Shared preferences.

  • Read data

Similarly getter methods are provided to retrieve local data. For each setter type there is a corresponding getter. Here the saved key ‘counter’ is read through getInt() method. Null safety check should also be used if the key isn’t present locally.

  • Remove data

Remove method removes the unused key from the Shared Preference.

2) Files

In order to persist downloaded image from internet, log files, csv files and any data other than simple key-value pairs, then persisting in Files is the efficient option available.

Flutter provides File class which enables to open, close, read, write and delete files for the specified file path. Before saving data to a file, the location of the file has to be known.

path_provider package allows you to navigate through directories and files.

  • Locate the application directory

getApplicationDocumentsDirectory() method from path_provider gives authority to access Documents directory — a dedicated directory for the app to store app files.

  • Create a reference to the file

Here ‘path’ variable has the essential path for the Documents directory of that application and pass the filename as a parameter to File object to reference the file.

  • Writing data in files

Once you created a reference to the file, you can write data to that file.

Here writeAsString() method from file class writes the file with the data in String type. Normally, Data are stored in type String just to achieve Serialization — a technique used to save and retrieve data without data structure complexion.

SERIALIZATION

Serialization is a way to convert JSON objects into String object. It offers a very powerful way to store and retrieve data without datatype dependency. Storing data in the form of Files require Serialization and deserialization the most.

  • Reading data in files

Similarly, reading data from a file requires the datatype of the stored data. Once you achieved Serialization, then String would be the datatype of the stored data. Then you can parse the data in the type you want. Here ‘contents’ are getting read as STRING and parsed to INT type.

3. SQLite

If your application requires large amounts of data to persist locally and want the retrieval should only happen through SQL queries, then Flutter suggests to use SQLite database than storing in files. The plugin Sqflite is written to perform CRUD operations on local SQLite databases.

  • Add the dependency

To add the packages as a dependency, run flutter pub add:

$ flutter pub add sqflite path
  • Defining the data model

Before creating the table to store information, define a model class for the object getting stored.

Here, employee data are getting stored.

  • Initiate Database connection and create a table

Before reading and writing data to database, open a connection with the local database instance.

OpenDatabase() method from sqflite enables connection with the local SQlite db. By setting proper path to the database from getDatabasesPath() function caller, we can initiate the connection successfully.

Here table employee_data is getting created using CREATE TABLE SQL query. emp_id is stored as INTEGER SQLite datatype and here it acts as a primary key for the table. emp_name is stored as TEXT datatype and similarly emp_role is also stored as TEXT datatype.

For more information about the available Datatypes that can be stored in a SQLite database, see the official SQLite Datatypes documentation.

  • Store data into data table

Get the reference to the database and insert data in table using insert() method.

  • Retrieve data from data table

To retrieve data from database, use query() method and pass table name as arguments

Here all employee data stored in employees table are retrieved as a list and converted into the respective Employee object.

  • Updation of data table

After inserting data into data table, you might want to update the data later. Update() method from sqflite package allows you to update table.

db.update() uses whereArgs to pass arguments to a where statement to ensure right object is identified and updation occurs. Here in this case, emp_id is used to identify ‘kumar’ record. Since emp_id acts as a primary key for the data table. Once ‘kumar’ record is fetched, it updates his role to “SDE 3”. This also helps to prevent SQL injection attacks.

  • Deletion of a record in data table

If a record is no longer used and occupying some amount of memory, it’s better to remove record from the data table than keep storing for long run. Sqflite library provides delete() method to remove data from the table.

Here passing an emp_id to deleteEmployee() method can delete the record for which the emp_id matched to in the data table.

Conclusion

In conclusion, application requires data to run efficiently but prompting from user everytime is tiresome. Storing data locally uses the same data everytime with the user concern and avoid unnecessary prompting on the application with no data leak. In this article, we have seen many techniques how data are getting stored locally for Flutter applications.

About the Author

Dhanesh started his journey as a Software Engineer Intern at CodeStax.Ai. He is an enthusiastic learner with the interest of exploring new technologies and with a passion for problem solving.

About CodeStax.Ai

At CodeStax.Ai, we stand at the nexus of innovation and enterprise solutions, offering technology partnerships that empower businesses to drive efficiency, innovation, and growth, harnessing the transformative power of no-code platforms and advanced AI integrations.

But the real magic? It’s our tech tribe behind the scenes. If you’ve got a knack for innovation and a passion for redefining the norm, we’ve got the perfect tech playground for you. CodeStax.Ai offers more than a job — it’s a journey into the very heart of what’s next. Join us, and be part of the revolution that’s redefining the enterprise tech landscape.

--

--

CodeStax.Ai
CodeStax.Ai

Written by CodeStax.Ai

Tech tales from our powerhouse Software Engineering team!

Responses (1)