step_db.dart 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import 'dart:async';
  2. import 'package:path/path.dart';
  3. import 'package:sport/provider/bluetooth.dart';
  4. import 'package:sqflite/sqflite.dart';
  5. class StepDB {
  6. static final StepDB _instance = new StepDB.internal();
  7. factory StepDB() => _instance;
  8. static Database? _db;
  9. StepDB.internal();
  10. Future<Database> get db async {
  11. if (_db != null) {
  12. return _db!;
  13. }
  14. _db = await initDb();
  15. return _db!;
  16. }
  17. final String TABLE = 'step';
  18. initDb() async {
  19. String databasesPath = await getDatabasesPath();
  20. String path = join(databasesPath, 'step.db');
  21. var db = await openDatabase(path, version: 2, onCreate: _onCreate, onUpgrade: _onUpgrade);
  22. return db;
  23. }
  24. FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
  25. if (newVersion > oldVersion) {
  26. try {
  27. await db.execute("drop table $TABLE");
  28. } catch (e) {
  29. print(e);
  30. }
  31. }
  32. await _onCreate(db, newVersion);
  33. }
  34. FutureOr<void> _onCreate(Database db, int version) async {
  35. await db.execute(
  36. 'CREATE TABLE $TABLE(time INTEGER PRIMARY KEY, step INTEGER, distance INTEGER)');
  37. }
  38. Future<int> insert(PartItem item) async {
  39. var dbClient = await db;
  40. var result = await dbClient.insert(TABLE, item.toJson());
  41. return result;
  42. }
  43. Future insertAll(List<PartItem> items) async {
  44. var dbClient = await db;
  45. var batch = dbClient.batch();
  46. items.forEach((item) {
  47. batch.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
  48. });
  49. batch.commit();
  50. }
  51. Future<List<Map<String, dynamic>>> find(int start) async {
  52. var dbClient = await db;
  53. return await dbClient.rawQuery(
  54. 'SELECT SUM(step) as st, SUM(distance) as di, time FROM $TABLE where time >= $start GROUP BY time ORDER BY time');
  55. }
  56. Future<int> delete(int time) async {
  57. var dbClient = await db;
  58. return await dbClient.delete(TABLE, where: "time <= ?", whereArgs: [time]);
  59. }
  60. }