How to Persist data locally with sqflite and sync to an Api in Flutter. (Part 1)

Hi ๐Ÿ™‚! This is part 1 of a series I want to use to teach you how to persist data on your device when there is no internet connection and sync that data to an API when there is internet connection. This article will also teach you how to check for internet connection on a device for a small price. haha! just kidding! it's free lol!

So recently, I got a gig to develop an app that requires the data to be stored on the device and also to be sent to an API. There aren't many resources that can help you achieve this, so out of my generosity ๐Ÿ˜‚, I'm sharing this.

I assume you already know how to setup a flutter project. If you don't know how to do that check -> Flutter.

Moving on, the first thing you want to do is setup the models and the SQLite database. I like to keep my code structure arranged and easily accessible. You'd want to create two folders in your lib -> models and local_db.

Screenshot (93).png

Add a dart file to the models folder. I call mine demand_model.dart. This is a regular model file in dart which has the tojson and fromjson methods.

The next thing you want to do is add a dart file to the local_db folder we created just created. Call it any thing you want !. I call mine db_helper.dart.

Inside the db_helper.dart, I will add these lines of code. They have comments above them describing what function they perform.

Create a simple UI, that has a textfield and a button that takes the user to the camera to snap and image and save. See my UI Code below: Please note that some of the reusable widgets shown are not in the code snippets. I would link the repo for the full code at the end of the article.

We have been able to send data to our SQLite database in this part. In part 2, I will show you how to send that data stored in the SQLite database to an API.

ย