insertItem method

Future<int> insertItem({
  1. required String tableName,
  2. required Map<String, dynamic> item,
  3. required String id,
  4. bool updateFallback = false,
})

Implementation

Future<int> insertItem({
  required String tableName,
  required Map<String, dynamic> item,
  required String id,
  bool updateFallback = false,
}) async {
  final db = await database;
  await _createTableIfNotExists(tableName: tableName, item: item);

  final now = DateTime.now().toIso8601String();
  item['date_added'] = now;
  item['last_updated'] = now;
  item['id'] = id;

  final serialized = _serializeItem(item);

  final exists = await this.exists(tableName: tableName, id: id);
  if (exists) {
    if (!updateFallback) return -1;
    return await db.update(
      tableName,
      serialized,
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  return await db.insert(
    tableName,
    serialized,
    conflictAlgorithm: sqflite.ConflictAlgorithm.replace,
  );
}