INSERT and SELECT
- Flutter course
- Intermediate
- Lesson 44/99
- 4 min
Insert and read data with db.insert and db.query.
Querying records
To read records from a table, you use the db.query method. The return value is a List<Map>; each Map represents a row.
final rows = await db.query('users');
for (final row in rows) {
print(row['name']);
}Rows are accessed by column names.
Iterating rows
You iterate over the List<Map> returned by db.query with a for loop. You access each row's columns via row['columnName'].
final rows = await db.query('users');
for (final row in rows) {
print('name: ${row['name']}');
}This way you can list all records.
Practice List all users
In the Veritabani class, write a tumKullanicilar method; call db.query('kullanicilar') and return the result. In main, call tumKullanicilar and print each row's 'isim' value with print('isim: ${satir['isim']}').
Starter code
import 'package:sqflite/sqflite.dart';
class Veritabani {
late Database db;
Future<void> ac() async {
db = await openDatabase('uygulama.db');
}
// tumKullanicilar metodu ekle
}
void main() async {
final vt = Veritabani();
await vt.ac();
// satırları gez ve isimleri yazdır
}Sample solution
import 'package:sqflite/sqflite.dart';
class Veritabani {
late Database db;
Future<void> ac() async {
db = await openDatabase('uygulama.db');
}
Future<List<Map<String, dynamic>>> tumKullanicilar() async {
return await db.query('kullanicilar');
}
}
void main() async {
final vt = Veritabani();
await vt.ac();
final satirlar = await vt.tumKullanicilar();
for (final satir in satirlar) {
print('isim: ${satir['isim']}');
}
}Expected output
isim: Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does db.query return?
- A String
- Rows as List<Map> Correct answer
- A Future<void>
- A single int
Explanation: db.query returns the rows as List<Map>; each Map represents a row.
2 Read records with db.query
final satirlar = await db.____('kullanicilar');
for (final satir in satirlar) {
print(satir['isim']);
}
final satirlar = await db.query('kullanicilar');
for (final satir in satirlar) {
print(satir['isim']);
}
Explanation: db.query returns rows from the table as List<Map>; the for loop iterates each row.
3 Query records parts
| Term | Meaning |
|---|---|
db.query |
Method reading rows from table |
List<Map> |
Return type representing rows |
for döngüsü |
Way to iterate rows |
satir['isim'] |
Access to column value |