Search code examples
sqliteflutterdatatablescompanion-objectsqflite

When do we use Companion in tables in Flutter?


I have seen many flutter sqfLite based codes using (TableName)sCompanion instead of (TableName)s.

What is the advantage of using this over the former?


Solution

  • Let's say your table's name is Task.

    class Tasks extends Table{
     IntColumn get taskid => integer().autoIncrement()(); 
     TextColumn get title => text().withLength(min:1,max:20)();
    
    }
    

    This table consists of taskid which autoIncrements itself without the need of user's input. Now if we were to use:

    Task(
     title: data,
    );
    

    instead of:

    TasksCompanion(
     title: Value(data),
    );
    

    There may be an error saying that the taskid is required but not given any value. So whenever we have an autoIncrement value or let's say you don't want to fill out every field( taskid,title etc.). Then we use Companions to give values to only limited fields.