Search code examples
sqliteflutterpersistenceconverters

How to convert Boolean Value to Int value using Sqlite in Flutter?


Using flutter I have this model

  class Task {
  String color;
  String env;
  String id;
  String name;
  String description;
  bool isBuyIt;
  bool isOnBacklog;
 }

I am using SwitchListTile in order to change the boolean value of isBuyIt and isOnBacklog

SwitchListTile(
              activeColor: HexColor(task.color),
              title: Text("Do you have it?"),
              value: task.isBuyIt,
              onChanged: (bool value) {
                setState(() {
                  task.isBuyIt = value;
                });
              },
              secondary: IconButton(
                icon: Icon(Icons.shopping_cart),
                onPressed: null,
                color: HexColor(task.color),
              ),
            ) 

I am using sqflite: ^1.3.0 and as you know it does not support bool value. I made the table like this way:

  Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId TEXT PRIMARY KEY,
            $columnName TEXT NOT NULL,
            $columnColor TEXT NOT NULL,
            $columnEnv TEXT NOT NULL,
            $columnDescription TEXT NOT NULL,
            $columnisBuyIt INTEGER NOT NULL,
            $columnisOnBacklog INTEGER NOT NULL
          )
          ''');
  }

But I dont know how to convert Boolean value into Integer value. I dont want to change the model fields to Integer because SwitchListTiledoesnt works with INT value

I guess Check Constraint would work.


Solution

  • Starting from SQLite 3.23.0 literal true/false are recognized and could be used.

    Recognize TRUE and FALSE as constants. (For compatibility, if there exist columns named "true" or "false", then the identifiers refer to the columns rather than Boolean constants.)

    CREATE TABLE a (id INT, i BOOLEAN);
                                      
    INSERT INTO a(id,i) VALUES(10,true);
    INSERT INTO a(id,i) VALUES(20, false);
    
    SELECT * FROM a;
    

    db-fiddle.com