After modified sqflite table, application will be crashed

I added a new column to sqflite database. After that, I can't use my application when update application. I should uninstall and re-install. How to handle this kind of situation?

class HelperDatabase1 {
  static final HelperDatabase1 _instance = HelperDatabase1.internal();

  factory HelperDatabase1() => _instance;
  static Database _db;

  Future<Database> get db1 async {
    if (_db != null) return _db;
    _db = await initDb();
    return _db;
  }

  HelperDatabase1.internal();

  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "HelperDatabase.db");
    var theDb = await openDatabase(path, version: 2, onCreate: _onCreate);
    return theDb;
  }

  void _onCreate(Database db, int version) async {
await db.execute("CREATE TABLE GetUserPreferenceTable(id INTEGER PRIMARY KEY AUTOINCREMENT, data INTEGER)");
}

in my main.dart

var helper;

void main() async {
  // debugPaintSizeEnabled=false;
  helper =
  await HelperDatabase1(); 

1 answer

  • answered 2019-05-21 16:31 Josh Sullivan

    Without seeing your specific error, it is likely that you need to increment your database's version number in the openDatabase() method to notify of a schema change.

    For example, if you are using code similar to the following to create your database, you would increment the version from 1 to 2:

    createDatabase() async {
      String databasesPath = await getDatabasesPath();
      String dbPath = join(databasesPath, 'my.db');
    
      var database = await openDatabase(dbPath, version: 2, onCreate: populateDb);
      return database;
    }