import 'dart:async'; import 'package:flutter_reactive_ble/flutter_reactive_ble.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; class BluetoothDB { static final BluetoothDB _instance = new BluetoothDB.internal(); factory BluetoothDB() => _instance; static Database? _db; BluetoothDB.internal(); Future get db async { if (_db != null) { return _db!; } _db = await initDb(); return _db!; } static final String TABLE = 'bluetooth'; static final String C_ID = 'id'; static final String C_NAME = 'name'; static final String C_MARK = 'mark'; static final String C_TIMES = 'times'; initDb() async { String databasesPath = await getDatabasesPath(); String path = join(databasesPath, 'bluetooth.db'); var db = await openDatabase(path, version: 2, onCreate: _onCreate, onUpgrade: _onUpgrade); return db; } FutureOr _onUpgrade(Database db, int oldVersion, int newVersion) async { if (newVersion > oldVersion) { try { await db.execute("drop table $TABLE"); } catch (e) { print(e); } } await _onCreate(db, newVersion); } FutureOr _onCreate(Database db, int version) async { await db.execute('CREATE TABLE $TABLE($C_ID VARCHAR PRIMARY KEY,$C_NAME VARCHAR, $C_MARK VARCHAR, $C_TIMES INTEGER)'); } Future insert(DiscoveredDevice item, {String? mark}) async { var dbClient = await db; var history = await find(); if (history.any((element) => element[BluetoothDB.C_ID] == item.id)) { if (mark == null) { return await dbClient.update(TABLE, {C_TIMES: DateTime.now().millisecondsSinceEpoch}, where: "$C_ID = ?", whereArgs: [item.id]); } else { return await dbClient.update(TABLE, {C_TIMES: DateTime.now().millisecondsSinceEpoch, C_MARK: mark}, where: "$C_ID = ?", whereArgs: [item.id]); } } else { return await dbClient.insert(TABLE, {C_ID: item.id, C_NAME: item.name, C_MARK: mark, C_TIMES: DateTime.now().millisecondsSinceEpoch}, conflictAlgorithm: ConflictAlgorithm.replace); } } Future>> findById(String id) async { var dbClient = await db; return await dbClient.rawQuery('SELECT $C_ID,$C_NAME,$C_MARK, $C_TIMES FROM $TABLE where $C_ID = "$id"'); } Future>> find() async { var dbClient = await db; return await dbClient.rawQuery('SELECT $C_ID,$C_NAME,$C_MARK, $C_TIMES FROM $TABLE order by $C_TIMES desc'); } }