Flutter sqlite boolean

Flutter SQLite Boolean

In Flutter, you can use SQLite as a local database to store and retrieve data. SQLite does not have a native boolean data type, but you can use other data types to represent boolean values.

Typically, the INTEGER data type is used to represent boolean values in SQLite. You can use a value of 0 to represent false and a value of 1 to represent true.

When working with SQLite in Flutter, you can use the sqflite package, which provides a set of APIs for interacting with SQLite databases.

Example:

Here’s an example of creating a table with a boolean column and inserting records with boolean values using the sqflite package in Flutter:


import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

void main() async {
  // Open the database
  Database database = await openDatabase(
    join(await getDatabasesPath(), 'my_database.db'),
    version: 1,
    onCreate: (db, version) async {
      // Create the table
      await db.execute(
        'CREATE TABLE my_table (id INTEGER PRIMARY KEY, is_active INTEGER)',
      );
    },
  );

  // Insert records with boolean values
  await database.insert('my_table', {'id': 1, 'is_active': 1}); // true
  await database.insert('my_table', {'id': 2, 'is_active': 0}); // false

  // Retrieve records with boolean values
  List> result = await database.query('my_table');
  result.forEach((record) {
    int id = record['id'];
    bool isActive = record['is_active'] == 1;
    print('Record ID: $id, Is Active? $isActive');
  });
}
    

In this example, a table called my_table is created with two columns: id and is_active. The is_active column is of type INTEGER to represent boolean values.

Two records are inserted into the table: one with is_active as 1 (true) and another with is_active as 0 (false).

To retrieve the records, the query method is used, and the is_active value is converted to a boolean by comparing it with 1. The result is printed to the console.

Leave a comment