Add the sqflite and path packages, open the database with openDatabase, create tables in onCreate, then use insert and query for data.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
Future<Database> openAppDb() async {
final path = join(await getDatabasesPath(), 'app.db');
return openDatabase(
path,
version: 1,
onCreate: (db, version) => db.execute(
'CREATE TABLE notes(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL)',
),
);
}
Future<void> demo() async {
final db = await openAppDb();
await db.insert('notes', {'title': 'Buy milk'});
final rows = await db.query('notes', where: 'title LIKE ?', whereArgs: ['%milk%']);
print(rows); // [{id: 1, title: Buy milk}]
}- Always pass user input through
whereArgs, never by string concatenation. - Raise
versionand handleonUpgradewhen you change the schema. sqflitetargets Android, iOS and macOS. For desktop and tests usesqflite_common_ffi.- For type-safe queries and migrations,
driftbuilds on SQLite with code generation.
