1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- import 'dart:async';
- import 'package:path/path.dart';
- import 'package:sport/provider/bluetooth.dart';
- import 'package:sqflite/sqflite.dart';
- class StepDB {
- static final StepDB _instance = new StepDB.internal();
- factory StepDB() => _instance;
- static Database? _db;
- StepDB.internal();
- Future<Database> get db async {
- if (_db != null) {
- return _db!;
- }
- _db = await initDb();
- return _db!;
- }
- final String TABLE = 'step';
- initDb() async {
- String databasesPath = await getDatabasesPath();
- String path = join(databasesPath, 'step.db');
- var db = await openDatabase(path, version: 2, onCreate: _onCreate, onUpgrade: _onUpgrade);
- return db;
- }
- FutureOr<void> _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<void> _onCreate(Database db, int version) async {
- await db.execute(
- 'CREATE TABLE $TABLE(time INTEGER PRIMARY KEY, step INTEGER, distance INTEGER)');
- }
- Future<int> insert(PartItem item) async {
- var dbClient = await db;
- var result = await dbClient.insert(TABLE, item.toJson());
- return result;
- }
- Future insertAll(List<PartItem> items) async {
- var dbClient = await db;
- var batch = dbClient.batch();
- items.forEach((item) {
- batch.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
- });
- batch.commit();
- }
- Future<List<Map<String, dynamic>>> find(int start) async {
- var dbClient = await db;
- return await dbClient.rawQuery(
- 'SELECT SUM(step) as st, SUM(distance) as di, time FROM $TABLE where time >= $start GROUP BY time ORDER BY time');
- }
- Future<int> delete(int time) async {
- var dbClient = await db;
- return await dbClient.delete(TABLE, where: "time <= ?", whereArgs: [time]);
- }
- }
|