Flutter
Summary - sqflite
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.
Exercise 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']}'.
Show example 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']}');
}
}
Test yourself
-
Which method is used to add a new note to the database in the notes app?
- db.execute
- db.delete
- db.query
- db.insert
Show answer
db.insert — To add a new note, db.insert is used; column values are given as a Map.
-
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)');
},
)
Show answer
await openDatabase(
'uygulama.db',
version: 1,
onCreate: (db, version) async {
await db.execute('CREATE TABLE notlar (id INTEGER PRIMARY KEY, baslik TEXT)');
},
)
-
sqflite section parts
- openDatabase
- Method opening the database
- onCreate
- Defines tables on first open
- insert
- Inserts a record into the table
- query
- Reads rows from the table
Next lesson: What is the http package?