-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite.dart
61 lines (49 loc) · 1.58 KB
/
sqlite.dart
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
// ignore_for_file: non_constant_identifier_names
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:io' as io;
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database? _db;
Future<Database> get db async {
if (_db != null) {
return _db!;
}
_db = await initDb();
return _db!;
}
String TABLE = "MY_TABLE_NAME";
DatabaseHelper.internal();
initDb() async {
io.Directory documnentDirectory = await getApplicationDocumentsDirectory();
String path = join(documnentDirectory.path, "main.db");
var database = await openDatabase(path, version: 1, onCreate: _onCreate);
return database;
}
void _onCreate(Database db, int version) async {
await db.execute("CREATE TABLE " +
TABLE +
"(id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT, avatar TEXT, role TEXT);");
print(" Table is created");
}
//fetch
Future<List<Map<String, dynamic>>> getDataToList() async {
var dbClient = await db;
var result = await dbClient.query(TABLE);
return result;
}
//insertion
Future<int> saveItemToDB(Map<String, Object?> object) async {
var dbClient = await db;
int result = await dbClient.insert(TABLE, object);
return result;
}
//Deletion.
Future<int> deleteItemFromDB(String table, int id) async {
var dbClient = await db;
int result = await dbClient.delete(table, where: "id = ?", whereArgs: [id]);
return result;
}
}