123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import 'dart:io';
- import 'package:dio/dio.dart';
- import 'package:drift/drift.dart';
- import 'package:drift/native.dart';
- import 'package:lszlgl/main.dart';
- import 'package:lszlgl/model/req/device_req.dart';
- import 'package:path_provider/path_provider.dart';
- import 'package:path/path.dart' as p;
- import '../network/my_api.dart';
- import '../service/user_service.dart';
- import 'dao/device_info_table_dao.dart';
- import 'device_info_table.dart';
- part 'database.g.dart';
- @DriftDatabase(tables: [DeviceInfoTable], daos: [DeviceInfoTableDao])
- class MyDatabase extends _$MyDatabase {
- MyDatabase() : super(_openConnection());
- // MyDatabase(super.e);
- @override
- int get schemaVersion => 1;
- /// 同步数据到服务器
- Future<void> savaBleDataToServer() async {
- List<DeviceInfo> deviceInfos = await database.deviceInfoTableDao.queryAllDeviceInfo();
- List<DeviceReq> deviceRes = [];
- for(DeviceInfo device in deviceInfos) {
- deviceRes.add(DeviceReq.fromJson(device.toJson()));
- }
- if(deviceRes.isEmpty) {
- return;
- }
- try {
- // 获取用户数据
- var user = await MyApi.get().postDeviceInfos(deviceRes);
- logger.d('====user:$user');
- // 记录末次同步id
- UserService.get().saveDeviceInfoTableTime(deviceInfos.last.createdAt);
- } on DioException catch (_) {
- } on Exception catch (a, _) {
- }
- }
- }
- LazyDatabase _openConnection() {
- return LazyDatabase(() async {
- final documentsDir = await getApplicationDocumentsDirectory();
- final file = File(p.join(documentsDir.path, 'myDatabase.db'));
- return NativeDatabase.createInBackground(file);
- });
- }
|