Summary - sqflite
- Flutter course
- Intermediate
- Lesson 45/99
- 4 min
Combine openDatabase, CREATE and INSERT to make a notes store.
Summary - sqflite
In this section you learned three things: with sqflite you open a local SQLite database; with onCreate and execute you create tables; with insert and query you add and read records.
final db = await openDatabase('app.db',
onCreate: (db, v) async {
await db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
},
);
await db.insert('users', {'name': 'Ayşe'});
final rows = await db.query('users');Combining these, you build a notes app.
Practice Build a notes app
In the Veritabani class, write ac, notEkle and tumNotlar methods. In ac, with openDatabase create the notlar (id INTEGER PRIMARY KEY, baslik TEXT) table in onCreate. notEkle should call db.insert('notlar', {'baslik': baslik}). tumNotlar should return db.query('notlar'). In main, call notEkle('Alışveriş'), then iterate all notes and print 'baslik: ${satir['baslik']}'.
Starter code
import 'package:sqflite/sqflite.dart';
class Veritabani {
late Database db;
// ac, notEkle ve tumNotlar metotları ekle
}
void main() async {
final vt = Veritabani();
// ac, notEkle çağır ve tüm notları yazdır
}Sample solution
import 'package:sqflite/sqflite.dart';
class Veritabani {
late Database db;
Future<void> ac() async {
db = await openDatabase(
'uygulama.db',
version: 1,
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notlar (id INTEGER PRIMARY KEY, baslik TEXT)'
);
},
);
}
Future<int> notEkle(String baslik) async {
return await db.insert('notlar', {'baslik': baslik});
}
Future<List<Map<String, dynamic>>> tumNotlar() async {
return await db.query('notlar');
}
}
void main() async {
final vt = Veritabani();
await vt.ac();
await vt.notEkle('Alışveriş');
final satirlar = await vt.tumNotlar();
for (final satir in satirlar) {
print('baslik: ${satir['baslik']}');
}
}Expected output
baslik: Alışveriş
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is used to add a new note to the database in the notes app?
- db.execute
- db.delete
- db.query
- db.insert Correct answer
Explanation: To add a new note, db.insert is used; column values are given as a Map.
2 Give onCreate to openDatabase
await openDatabase(
'uygulama.db',
version: 1,
____: (db, version) async {
await db.execute('CREATE TABLE notlar (id INTEGER PRIMARY KEY, baslik TEXT)');
},
)
await openDatabase(
'uygulama.db',
version: 1,
onCreate: (db, version) async {
await db.execute('CREATE TABLE notlar (id INTEGER PRIMARY KEY, baslik TEXT)');
},
)
Explanation: openDatabase's onCreate callback is called when the database is first created and tables are defined here.
3 sqflite section parts
| Term | Meaning |
|---|---|
openDatabase |
Method opening the database |
onCreate |
Defines tables on first open |
insert |
Inserts a record into the table |
query |
Reads rows from the table |