Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sync flutter app's offline data with online database efficiently

lets say I have a todo app that stores the data in sqflite database(locally on the phone) when the app goes online I want the data to be synced with my online database say mongodb or firestore.I don't want to do complete overwrites or creating the new table everytime,I am looking for some efficient solution that only updates the changes to the database.

like image 366
Mahesh Jamdade Avatar asked Sep 11 '19 04:09

Mahesh Jamdade


People also ask

Can flutter apps work offline?

✈️ Flutter Offline A tidy utility to handle offline/online connectivity like a Boss. It provides support for both iOS and Android platforms (offcourse).


Video Answer


3 Answers

Firebase Cloud Firestore makes all of this for you. If You can't use this, other solution is much more complicated as syncing information can be very tricky.

Imagine the user has 2 devices, both saving the same data, which version should the server keep, the newest created data, or the data the server received first?

SQLite is good for structured data, but you could save your data as a JSON string using System Preferences and just push that JSON to the server, it's a lot simpler if can do it this way.

Again, this really not a simple answer to give and varies from project to project.

like image 150
Michel Feinstein Avatar answered Oct 18 '22 21:10

Michel Feinstein


I think this will help to construct offline and online sync:

flutter_offline

http

sqlite

like image 8
Lydan Avatar answered Oct 18 '22 22:10

Lydan


As already pointed out, this is an architectural question and there's probably no simple answer. Here are two main thoughts :

Scenario A : You are just updating the transaction data and sequence doesn't matter e.g. mobile attendance app. The user's location along with date time stamp is recorded on the server. And server does everything else (validation, processing, reporting).

Scenario B : Sequence does matter. If you just keep the offline connectivity then older data may overwrite newer data in the following like scenario : user has two devices. the device having new data comes online first followed by the device with old data

I'd dealt with both of the scenarios and for scenario B, I did the following :

  1. Created a 'queue' table.
  2. All the entries first goes to the queue (online or offline)
  3. The inserts in the queue entry triggers Firebase Cloud function. The function does the validations and processing (example below).
  4. The function makes the entry in the actual table.

Step 3 is particularly useful when working with apps such as Todo. It is because you might want to log the event (say in the log file) but not to udpate the todo item status if older data comes later.

like image 4
Sukhi Avatar answered Oct 18 '22 22:10

Sukhi