Dart
sqflite
Learn SQLite with sqflite.
sqflite
sqflite is an embedded SQLite database package for Dart and Flutter. It stores data locally in a file; no server needed. It offers an async API: you open with openDatabase and run SQL with db.execute.
Example: final db = await openDatabase('notes.db'); opens a database. await db.execute('CREATE TABLE notes (...)'); creates a table. All calls are awaited; so main is usually async.
Database setup
When setting up a database you first open with openDatabase, then create a table with db.execute. The table structure is written in SQL: CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT, body TEXT).
When done you close the connection with await db.close(). Always closing is a good habit to avoid resource leaks. In this lesson we will write a helper function setupDb; we will reuse it in the next lessons.
Exercise Database setup function
Add import 'package:sqflite/sqflite.dart';. Define Future<Database> setupDb() async { ... }: open with openDatabase('notes.db'), create the table with db.execute('CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT, body TEXT)') and return db. In main add print('sqflite ready: notes.db') and print('Table: notes (id, title, body)'), then call await setupDb().
Show example solution
import 'package:sqflite/sqflite.dart';
Future<Database> setupDb() async {
final db = await openDatabase('notes.db');
await db.execute('CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT, body TEXT)');
return db;
}
void main() async {
print('sqflite ready: notes.db');
print('Table: notes (id, title, body)');
await setupDb();
}
Test yourself
-
What does sqflite provide?
- Web server
- Cloud storage
- Embedded SQLite
- In-memory cache
Show answer
Embedded SQLite — sqflite provides an embedded SQLite database.
-
Opening a database
Future<Database> setupDb() async {
final db = await ____('notes.db');
await db.execute('CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT, body TEXT)');
return db;
}
Show answer
Future<Database> setupDb() async {
final db = await openDatabase('notes.db');
await db.execute('CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT, body TEXT)');
return db;
}
-
Match the sqflite parts
- sqflite
- Embedded SQLite
- openDatabase
- Opens the database
- db.execute
- Runs SQL
- db.close
- Closes the connection
Next lesson: Database