Adds drone model, db helper.

This commit is contained in:
2025-07-04 17:19:46 +02:00
parent 0266bf924b
commit fb6a20fd75
13 changed files with 1039 additions and 3 deletions

81
lib/db/db_helper.dart Normal file
View File

@ -0,0 +1,81 @@
// Singleton to access database
import 'dart:developer';
import 'dart:io';
import 'package:path/path.dart';
import 'package:logging/logging.dart';
import '../models/drone.dart';
import 'package:path_provider/path_provider.dart';import 'package:sqflite/sqflite.dart';
class DbHelper
{
static final DbHelper instance = DbHelper._internal();
static final log = Logger("DbHelper");
static Database? _database;
DbHelper._internal();
Future<Database> get database async
{
if (_database != null) return _database!;
await _initDb();
return _database!;
}
Future _initDb() async
{
final directory = await getApplicationDocumentsDirectory();
final db_name = "rtime.db";
final path = join(directory.path, db_name);
log.info("Opeing database file at $path");
_database = await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
log.info("Database opened successfully !");
log.info("${(await getDrones()).length} drones in DB.");
}
Future _onCreate(Database db, int version) async
{
log.info("Database does not exist, creating a new one.");
await db.execute('''
CREATE TABLE drones(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
image TEXT
)
''');
}
Future<int> insertDrone(Drone drone) async
{
final db = await database;
return await db.insert("drones", drone.toMap());
}
Future<List<Drone>> getDrones() async
{
final db = await database;
final maps = await db.query("drones");
return maps.map((e) => Drone.fromMap(e)).toList();
}
Future<int> deleteItem(int drone_id) async
{
final db = await database;
return await db.delete("drones", where: "id = ?", whereArgs: [drone_id]);
}
Future closeDb() async
{
final db = await database;
log.info("Closing database.");
db.close();
_database = null;
}
}