import 'dart:convert'; import 'package:managerapi/api.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; import 'package:tablet_app/Models/tabletContext.dart'; class DatabaseHelper { static final _databaseName = "tablet_database.db"; static final _databaseVersion = 1; static final table = 'tabletAppContext'; static final columnId = 'id'; static final columnDeviceId = 'deviceId'; static final columnHost = 'host'; static final columnConfiguration = 'configuration'; static final columnLanguage = 'language'; DatabaseHelper._privateConstructor(); static final DatabaseHelper instance = DatabaseHelper._privateConstructor(); static Database _database; Future get database async { if (_database != null) return _database; _database = await _initDatabase(); return _database; } _initDatabase() async { String path = join(await getDatabasesPath(), _databaseName); return await openDatabase(path, version: _databaseVersion, onCreate: _onCreate); } // SQL code to create the database table Future _onCreate(Database db, int version) async { await db.execute(''' CREATE TABLE $table ( $columnId TEXT NOT NULL PRIMARY KEY, $columnDeviceId TEXT NOT NULL, $columnHost TEXT NOT NULL, $columnConfiguration TEXT, $columnLanguage TEXT NOT NULL ) '''); } Future insert(TabletAppContext tabletAppContext) async { Database db = await instance.database; var res = await db.insert(table, tabletAppContext.toMap()); return res; } Future update(TabletAppContext tabletAppContext) async { // Get a reference to the database. final db = await instance.database; await db.update( 'tabletAppContext', tabletAppContext.toMap(), where: "id = ?", whereArgs: ["1234"], // ); } Future>> queryAllRows() async { Database db = await instance.database; var res = await db.query(table, orderBy: "$columnId DESC"); return res; } Future delete(String email) async { Database db = await instance.database; return await db.delete(table, where: '$columnId = ?', whereArgs: [email]); } Future clearTable() async { Database db = await instance.database; return await db.rawQuery("DELETE FROM $table"); } Future getData() async { TabletAppContext tabletAppContext; await DatabaseHelper.instance.queryAllRows().then((value) { value.forEach((element) { print("DB - CONTEXT --- "); // Configuration is store in SQLite in JSON Format var configuration = element['configuration'] == null ? null: ConfigurationDTO.fromJson(jsonDecode(element['configuration'])); tabletAppContext = TabletAppContext( id: element["id"], deviceId: element["deviceId"], host: element["host"], configuration: configuration, language: element["language"] ); }); }).catchError((error) { print(error); }); return tabletAppContext; } }