databasefluttermigrationsqflitefloor

How can I alter my table column in Floor database with the help of Migration?


I Want update my table column in the Floor database with the help of changing my database version and run migrations. For example, I want to change column A to a nullable column! How can I achieve this goal? anybody can provide a sample code, please?


Solution

  • You can create a migration like this:

    
    //Step 1 - Update the version to (ex: from 1 to 2) inside the database annotation
    @Database(version: 1, entities: [Person, Task])
    abstract class AppDatabase extends FloorDatabase {
    
    //Step 2 - create the migration
    final migration1to2 = Migration(1, 2, (database) async {
      await database.execute('ALTER TABLE person ADD COLUMN nickname TEXT');
    });
    
    //Step 3 - then add it to the code that initialize the DB
    final database = await $FloorAppDatabase
        .databaseBuilder('app_database.db')
        .addMigrations([migration1to2])
        .build();
    

    full example of how to do it here: Migrations in Floor

    As for actual SQL to change it from not-null to nullable check this answer Modify Sqlite Table Column NOT NULL to NULL