Home > Back-end >  Share data while the Internet is available using flutter
Share data while the Internet is available using flutter

Time:08-08

I have a query I would like to store some data in the cache in the event that the phone is not connected to the Internet and when I connect to the Internet, it is sent to the server. I would like to know the best scenario for this case...

And thank u.

CodePudding user response:

You can try saving the data to the server and on failure you can write it in cache. Like

var response = await http.post(Uri.parse("api url here"),
          body: json.encode(body),
);
if(response.statusCode != 200)
{
  //save data in local like for example
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString("apiBody", json.encode(body);
}

CodePudding user response:

If you need to store or receive a large amount of data, consider to store this datas in a localdatabase like sqflite: https://pub.dev/packages/sqflite

base on SQLLite, you can store and manipulate data with SQL queries.

Here is an example DB helper call that manipulate customer datas:

class DBProvider {
  DBProvider._();

  static final DBProvider db = DBProvider._();

  late Database _database;

  Future<Database> get database async {
    _database = await initDB();
    return _database;
  }

  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(
      documentsDirectory.path,
      "andidoor.db",
    );

    return await openDatabase(
      path,
      version: 2,
      onOpen: (db) {},
      onCreate: createDatabase,
      onUpgrade: upgradeDatabase,
    );
  }

  upgradeDatabase(Database db, int oldVersion, int newVersion) async {
    print('Upgrade Database ...');
  }

  createDatabase(Database db, int version) async {
    print('Create Database ...');
    await db.execute("CREATE TABLE customers ("
        "id INTEGER PRIMARY KEY,"
        "user_id INTEGER,"
        "company TEXT,"
        "address_1 TEXT,"
        "address_2 TEXT,"
        "address_3 TEXT,"
        "zipcode TEXT,"
        "city TEXT,"
        "country TEXT,"
        "email TEXT,"
        "phone TEXT,"
        "status INTEGER,"
        "synced TEXT"
        ")");
  /**
   * Customers helper functions
   */

  Future<List<dynamic>> getCustomers() async {
    Database db = await database;
    return await db.rawQuery('SELECT * FROM customers ');
  }

  Future<void> populateCustomers(List<dynamic> customers) async {
    final completer = Completer();

    await deleteAllcustomers();

    for (var i = 0; i < customers.length; i  ) {
      await addCustomer(Customer.fromMap(customers[i]), true);
    }

    completer.complete();

    return completer.future;
  }

  Future<dynamic> deleteAllcustomers() async {
    Database db = await database;
    return await db.rawQuery('DELETE FROM customers');
  }

  Future<dynamic> deleteCustomer(String customerID) async {
    final db = await database;
    return db.delete(
      "customers",
      where: "id = ? ",
      whereArgs: [customerID],
    );
  }
}

And in other dart file just use like this:

final db = DBProvider.db;
List<dynamic> allDatas = [];
allDatas = await db.getCustomers();
  • Related