-1

I need to save a bool variable (true/false) in SQFLite.

I've seen that SQFlite does not support creating a bool column even though Dart supports booleans.

This means that I need to create an integer column and save a value with zero - > false and one -> true.

I don't know, may be it is better to save 1 -> false and 2 -> true.

In my program, I use a variable bool isChecked to refer to a UI control.

I don't think I can convert bool to int.

Could you please advise how to handle saving bool isChecked variable like 0 and 1.

Thank You

DktPhl2018
  • 155
  • 1
  • 1
  • 8
  • [floor](https://pub.dev/packages/floor) package would be a great alternative for you if you have worked with android [room](https://developer.android.com/training/data-storage/room) database – Yash Mar 31 '23 at 03:47

1 Answers1

0

You can try like this

final String tableTodo = 'todo';
final String columnId = '_id';
final String columnTitle = 'title';
final String columnDone = 'done';

class Todo {
  int id;
  String title;
  bool done;

  Map<String, Object?> toMap() {
    var map = <String, Object?>{
      columnTitle: title,
      columnDone: done == true ? 1 : 0
    };
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }

  Todo();

  Todo.fromMap(Map<String, Object?> map) {
    id = map[columnId];
    title = map[columnTitle];
    done = map[columnDone] == 1;
  }
}

class TodoProvider {
  Database db;

  Future open(String path) async {
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute('''
create table $tableTodo ( 
  $columnId integer primary key autoincrement, 
  $columnTitle text not null,
  $columnDone integer not null)
''');
    });
  }

  Future<Todo> insert(Todo todo) async {
    todo.id = await db.insert(tableTodo, todo.toMap());
    return todo;
  }

  Future<Todo> getTodo(int id) async {
    List<Map> maps = await db.query(tableTodo,
        columns: [columnId, columnDone, columnTitle],
        where: '$columnId = ?',
        whereArgs: [id]);
    if (maps.length > 0) {
      return Todo.fromMap(maps.first);
    }
    return null;
  }

  Future<int> delete(int id) async {
    return await db.delete(tableTodo, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<int> update(Todo todo) async {
    return await db.update(tableTodo, todo.toMap(),
        where: '$columnId = ?', whereArgs: [todo.id]);
  }

  Future close() async => db.close();
}

Source Sqflite Readme

Mofidul Islam
  • 378
  • 3
  • 12