How to sync remote DB MongoDB with local DB sqlite in flutter?

593

When your app receives data (JSON) data from the server, save your data as Map on Sqlite. But I'm not sure if Sqlite is able to save those kinds of formats. In my case, Im using cached_map library to save data from MongoDB then load data back and display it on my app.

Library: https://pub.dev/packages/cached_map

Below Example code.

class AppCache {
  static Mapped? mapped;

  static initCache() async {
    mapped = await Mapped.getInstance();
  }

  static saveCacheV2(dynamic value, String serverFeatures) async {
    String message = await Mapped.saveFileDirectly(
        file: value, cachedFileName: serverFeatures);
    print(message);
    // print("cache async save");
  }

  static Future<Map<String, dynamic>?> loadCacheV2(
      String serverFeatures) async {
    return await Mapped.loadFileDirectly(cachedFileName: serverFeatures);
  }

  static saveCache(dynamic value, String serverFeatures) {
    //save a file
    mapped?.saveFile(file: value, cachedFileName: serverFeatures);
  }

  static Map<String, dynamic>? loadCache(String serverFeatures) {
    return mapped?.loadFile(cachedFileName: serverFeatures);
  }
}

Save data

  AppCache.saveCacheV2(
          response.toMap(), ServerFeatures.jawatanKosongFunction);

Load data

var cache = AppCache.loadCacheV2(ServerFeatures.jawatanKosongFunction);
    cache.then((response) {
      if (response != null) {
        setValue(SenaraiJawatanKosongResponse.fromMap(response));
        print("cache load");
      }
    });
Share:
593
Shadman Nehal Khan
Author by

Shadman Nehal Khan

Updated on January 04, 2023

Comments

  • Shadman Nehal Khan
    Shadman Nehal Khan over 1 year

    I am assigned with a task to sync local DB(Sqlite) with Remote DB MongoDB and I am very new in flutter though I got idea how to implement local DB and MongoDB separately but don't know how to sync and make it available when data is offline.