database.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'dart:io';
  2. import 'package:dio/dio.dart';
  3. import 'package:drift/drift.dart';
  4. import 'package:drift/native.dart';
  5. import 'package:lszlgl/main.dart';
  6. import 'package:lszlgl/model/req/device_req.dart';
  7. import 'package:path_provider/path_provider.dart';
  8. import 'package:path/path.dart' as p;
  9. import '../network/my_api.dart';
  10. import '../service/user_service.dart';
  11. import 'dao/device_info_table_dao.dart';
  12. import 'device_info_table.dart';
  13. part 'database.g.dart';
  14. @DriftDatabase(tables: [DeviceInfoTable], daos: [DeviceInfoTableDao])
  15. class MyDatabase extends _$MyDatabase {
  16. MyDatabase() : super(_openConnection());
  17. // MyDatabase(super.e);
  18. @override
  19. int get schemaVersion => 1;
  20. /// 同步数据到服务器
  21. Future<void> savaBleDataToServer() async {
  22. List<DeviceInfo> deviceInfos = await database.deviceInfoTableDao.queryAllDeviceInfo();
  23. List<DeviceReq> deviceRes = [];
  24. for(DeviceInfo device in deviceInfos) {
  25. deviceRes.add(DeviceReq.fromJson(device.toJson()));
  26. }
  27. if(deviceRes.isEmpty) {
  28. return;
  29. }
  30. try {
  31. // 获取用户数据
  32. var user = await MyApi.get().postDeviceInfos(deviceRes);
  33. logger.d('====user:$user');
  34. // 记录末次同步id
  35. UserService.get().saveDeviceInfoTableTime(deviceInfos.last.createdAt);
  36. } on DioException catch (_) {
  37. } on Exception catch (a, _) {
  38. }
  39. }
  40. }
  41. LazyDatabase _openConnection() {
  42. return LazyDatabase(() async {
  43. final documentsDir = await getApplicationDocumentsDirectory();
  44. final file = File(p.join(documentsDir.path, 'myDatabase.db'));
  45. return NativeDatabase.createInBackground(file);
  46. });
  47. }