I am using a DBHelper class, and in one of my other classes calling the getter so that if DB is null it initializes it. In an another method I insert data returned from rest end point into the DB and get the above exception. I guess maybe as the record is already present I get the exception. In that case I would like to understand when does the DB gets created and the lifecycle. Mostly all articles on the web for sqflite are based on the CRUD operations.

Future<Database> get db async{
    if(_db == null){
        _db = await initializeDb();
    }
    return _db;
  }

Future<Database> initializeDb() async{
    Directory dir = await path_pro.getApplicationDocumentsDirectory();
    String path = dir.path + 'csr';
    var dbCsr = await openDatabase(path, version: 1, onCreate: _createDb);
    return dbCsr;
  }
  void _createDb(Database db, int newVersion) async{
    await db.execute(
      "CREATE TABLE $tblName($colPropId INTEGER PRIMARY KEY, $colCityName TEXT, $colPropName TEXT, $colPropAddr TEXT)"
    );
  }
  Future<int> insertProp(Map<String, dynamic> map) async{
    Database db = await this.db;
    var result = await db.insert(tblName, map);
    return result;
  }

In my other class i call it as below:

DBHelper().db

DBHelper().insertProp(element[i]);

Thanks


Solution 1: Mohammed Zoheyeb

In my DBHelper class in the insert method I'm using a select query first to check if there is an entry...If present I update it, If not I insert into the DB.

Future<int> insertProp(Map<String, dynamic> map) async{
    var result;
    Database db = await this.db;
    var count = Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) from 
                $tblName WHERE $colPropId = ? ', [map['prop_id']]));
    if(count == 0){
      result = await db.insert(tblName, map);
    }else{
       await db.update(tblName, map, where: '$colPropId = ?', whereArgs: 
      [map['prop_id']]);
    }
    return result;
  }

Thanks all