-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_helper.dart
More file actions
65 lines (54 loc) · 1.6 KB
/
database_helper.dart
File metadata and controls
65 lines (54 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._init();
static Database? _database;
DatabaseHelper._init();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDB('notes.db');
return _database!;
}
Future<Database> _initDB(String filePath) async {
final dbPath = await getDatabasesPath();
final path = join(dbPath, filePath);
return await openDatabase(path, version: 1, onCreate: _createDB);
}
Future _createDB(Database db, int version) async {
const idType = 'INTEGER PRIMARY KEY AUTOINCREMENT';
const textType = 'TEXT NOT NULL';
await db.execute('''
CREATE TABLE notes (
id $idType,
title $textType,
content $textType
)
''');
}
Future<void> insertNote(Map<String, dynamic> note) async {
final db = await instance.database;
await db.insert('notes', note);
}
Future<List<Map<String, dynamic>>> getNotes() async {
final db = await instance.database;
return await db.query('notes');
}
Future<int> updateNote(Map<String, dynamic> note) async {
final db = await instance.database;
final id = note['id'];
return db.update(
'notes',
note,
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> deleteNote(int id) async {
final db = await instance.database;
return await db.delete(
'notes',
where: 'id = ?',
whereArgs: [id],
);
}
}