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 savaBleDataToServer() async { List deviceInfos = await database.deviceInfoTableDao.queryAllDeviceInfo(); List 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); }); }