You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.7 KiB
58 lines
1.7 KiB
7 months ago
|
import 'dart:ffi';
|
||
|
import 'dart:io';
|
||
|
|
||
|
import 'package:counters/address.dart';
|
||
|
import 'package:path/path.dart';
|
||
|
import 'package:path_provider/path_provider.dart';
|
||
|
import 'package:sqflite/sqflite.dart';
|
||
|
|
||
|
class DBProvider {
|
||
|
static const int dbVersion = 1;
|
||
|
static const String addressTableName = 'address$dbVersion';
|
||
|
DBProvider._();
|
||
|
static final DBProvider db = DBProvider._();
|
||
|
|
||
|
static Database? _database;
|
||
|
Future<Database> get database async {
|
||
|
if (_database != null) return _database!;
|
||
|
|
||
|
_database = await initDB();
|
||
|
return _database!;
|
||
|
}
|
||
|
|
||
|
initDB() async {
|
||
|
Directory documentsDirectory = await getApplicationDocumentsDirectory();
|
||
|
String path = join(documentsDirectory.path, "counters.db");
|
||
|
print(path);
|
||
|
return await openDatabase(path, version: dbVersion, onOpen: (db) {},
|
||
|
onCreate: (Database db, int version) async {
|
||
|
await db.execute("CREATE TABLE $addressTableName ("
|
||
|
"id INTEGER PRIMARY KEY,"
|
||
|
"street_name TEXT,"
|
||
|
"comments TEXT"
|
||
|
")");
|
||
|
});
|
||
|
}
|
||
|
|
||
|
Future<int> newAddress(Address newAddress) async {
|
||
|
final db = await database;
|
||
|
var res = await db.insert(addressTableName, newAddress.toJson());
|
||
|
return res;
|
||
|
}
|
||
|
|
||
|
Future<Object> getAddress(int id) async {
|
||
|
final db = await database;
|
||
|
var res =
|
||
|
await db.query(addressTableName, where: "id = ?", whereArgs: [id]);
|
||
|
return res.isNotEmpty ? Address.fromJson(res.first) : Null;
|
||
|
}
|
||
|
|
||
|
Future<List<Address>> getAllAddress() async {
|
||
|
final db = await database;
|
||
|
var res = await db.query(addressTableName);
|
||
|
List<Address> list =
|
||
|
res.isNotEmpty ? res.map((c) => Address.fromJson(c)).toList() : [];
|
||
|
return list;
|
||
|
}
|
||
|
}
|