step_db.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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: 1, onCreate: _onCreate);
  22. return db;
  23. }
  24. FutureOr<void> _onCreate(Database db, int version) async {
  25. await db.execute('CREATE TABLE $TABLE(id INTEGER PRIMARY KEY, step INTEGER, distance INTEGER, time INTEGER)');
  26. }
  27. Future<int> insert(PartItem item) async {
  28. var dbClient = await db;
  29. var result = await dbClient.insert(TABLE, item.toJson());
  30. return result;
  31. }
  32. Future insertAll(List<PartItem> items) async {
  33. var dbClient = await db;
  34. var batch = dbClient.batch();
  35. items.forEach((item) {
  36. batch.insert(TABLE, item.toJson());
  37. });
  38. batch.commit();
  39. }
  40. Future<List<Map<String, dynamic>>> find() async {
  41. var dbClient = await db;
  42. return await dbClient.rawQuery('SELECT SUM(step) as st, SUM(distance) as di, time FROM $TABLE GROUP BY time ORDER BY time LIMIT 1000');
  43. }
  44. Future<int> delete(int time) async {
  45. var dbClient = await db;
  46. return await dbClient.delete(TABLE, where: "time <= ?", whereArgs: [time]);
  47. }
  48. }