refactor: split providers into feature modules
This commit is contained in:
29
lib/features/homes/geofence_task_sync.dart
Normal file
29
lib/features/homes/geofence_task_sync.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
import 'package:workmanager/workmanager.dart';
|
||||
|
||||
import '../../models/home_config.dart';
|
||||
import '../../services/geofence_worker.dart';
|
||||
|
||||
/// Синхронизировать состояние фонового таска с настройками домов.
|
||||
/// Вызывать при старте приложения и при изменении настроек.
|
||||
///
|
||||
/// Если хотя бы один дом имеет geofenceReady -- регистрируем
|
||||
/// периодический таск. Иначе -- отменяем.
|
||||
Future<void> syncGeofenceTask(List<HomeConfig> homes) async {
|
||||
final needGeofence = homes.any((h) => h.geofenceReady);
|
||||
|
||||
if (needGeofence) {
|
||||
await resetGeofenceFired();
|
||||
|
||||
await Workmanager().registerPeriodicTask(
|
||||
geofenceTaskUniqueName,
|
||||
geofenceTaskName,
|
||||
frequency: const Duration(minutes: 15),
|
||||
constraints: Constraints(networkType: NetworkType.connected),
|
||||
existingWorkPolicy: ExistingPeriodicWorkPolicy.replace,
|
||||
backoffPolicy: BackoffPolicy.linear,
|
||||
backoffPolicyDelay: const Duration(minutes: 1),
|
||||
);
|
||||
} else {
|
||||
await Workmanager().cancelByUniqueName(geofenceTaskUniqueName);
|
||||
}
|
||||
}
|
||||
101
lib/features/homes/providers/homes_providers.dart
Normal file
101
lib/features/homes/providers/homes_providers.dart
Normal file
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../models/home_config.dart';
|
||||
import '../../auth/providers/auth_providers.dart';
|
||||
import '../../shared/providers/core_providers.dart';
|
||||
|
||||
/// Текущий выбранный дом (null если ни одного нет)
|
||||
final currentHomeProvider = NotifierProvider<CurrentHomeNotifier, HomeConfig?>(
|
||||
() => CurrentHomeNotifier(),
|
||||
);
|
||||
|
||||
class CurrentHomeNotifier extends Notifier<HomeConfig?> {
|
||||
@override
|
||||
HomeConfig? build() => null;
|
||||
|
||||
/// Загрузить текущий дом из SharedPreferences
|
||||
Future<void> load() async {
|
||||
final svc = ref.read(settingsServiceProvider);
|
||||
state = await svc.getCurrentHome();
|
||||
if (state != null) {
|
||||
await _initApi(state!);
|
||||
}
|
||||
}
|
||||
|
||||
/// Переключиться на другой дом
|
||||
Future<void> switchTo(HomeConfig home) async {
|
||||
final svc = ref.read(settingsServiceProvider);
|
||||
await svc.setCurrentHomeId(home.id);
|
||||
state = home;
|
||||
await _initApi(home);
|
||||
}
|
||||
|
||||
/// Выбрать дом как активный и сразу проверить auth-state.
|
||||
/// Если `auth/me` падает, откатываемся к предыдущему дому и auth-state.
|
||||
Future<void> select(HomeConfig home) async {
|
||||
final previousHome = state;
|
||||
final previousAuthState = ref.read(authInfoProvider);
|
||||
|
||||
try {
|
||||
await switchTo(home);
|
||||
await ref.read(authInfoProvider.notifier).load(failOnError: true);
|
||||
} catch (error) {
|
||||
await _restoreSelection(previousHome);
|
||||
ref.read(authInfoProvider.notifier).restore(previousAuthState);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> clear() async {
|
||||
await ref.read(settingsServiceProvider).setCurrentHomeId(null);
|
||||
state = null;
|
||||
}
|
||||
|
||||
/// Инициализировать API-клиент текущим домом
|
||||
Future<void> _initApi(HomeConfig home) async {
|
||||
final apiKey = await ref
|
||||
.read(settingsServiceProvider)
|
||||
.requireHomeApiKey(home.id);
|
||||
ref.read(apiProvider).init(home.url, apiKey);
|
||||
}
|
||||
|
||||
Future<void> _restoreSelection(HomeConfig? home) async {
|
||||
if (home == null) {
|
||||
await clear();
|
||||
return;
|
||||
}
|
||||
|
||||
final svc = ref.read(settingsServiceProvider);
|
||||
await svc.setCurrentHomeId(home.id);
|
||||
state = home;
|
||||
await _initApi(home);
|
||||
}
|
||||
}
|
||||
|
||||
final homesProvider = NotifierProvider<HomesNotifier, List<HomeConfig>>(
|
||||
() => HomesNotifier(),
|
||||
);
|
||||
|
||||
class HomesNotifier extends Notifier<List<HomeConfig>> {
|
||||
@override
|
||||
List<HomeConfig> build() => [];
|
||||
|
||||
Future<void> load() async {
|
||||
state = await ref.read(settingsServiceProvider).getHomes();
|
||||
}
|
||||
|
||||
Future<void> add(HomeConfig home, {required String apiKey}) async {
|
||||
await ref.read(settingsServiceProvider).upsertHome(home, apiKey: apiKey);
|
||||
await load();
|
||||
}
|
||||
|
||||
Future<void> remove(String id) async {
|
||||
await ref.read(settingsServiceProvider).deleteHome(id);
|
||||
await load();
|
||||
}
|
||||
|
||||
Future<void> update(HomeConfig home, {String? apiKey}) async {
|
||||
await ref.read(settingsServiceProvider).upsertHome(home, apiKey: apiKey);
|
||||
await load();
|
||||
}
|
||||
}
|
||||
169
lib/features/homes/providers/location_providers.dart
Normal file
169
lib/features/homes/providers/location_providers.dart
Normal file
@@ -0,0 +1,169 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
|
||||
/// Состояние геолокации: позиция или причина отсутствия.
|
||||
/// Запрашивается один раз, кешируется до перезапуска провайдера.
|
||||
class UserLocation {
|
||||
final Position? position;
|
||||
final String? error; // null -- всё ок, иначе причина
|
||||
|
||||
const UserLocation({this.position, this.error});
|
||||
|
||||
bool get hasPosition => position != null;
|
||||
|
||||
/// Расстояние в км до точки. Возвращает null если нет позиции
|
||||
/// или у цели нет координат.
|
||||
double? distanceToKm(double? lat, double? lon) {
|
||||
if (position == null || lat == null || lon == null) return null;
|
||||
return calculateDistanceKm(
|
||||
position!.latitude,
|
||||
position!.longitude,
|
||||
lat,
|
||||
lon,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final userLocationProvider =
|
||||
NotifierProvider<UserLocationNotifier, UserLocation>(
|
||||
() => UserLocationNotifier(),
|
||||
);
|
||||
|
||||
class UserLocationNotifier extends Notifier<UserLocation> {
|
||||
StreamSubscription<Position>? _sub;
|
||||
int _watchers = 0;
|
||||
|
||||
@override
|
||||
UserLocation build() {
|
||||
ref.onDispose(() {
|
||||
_sub?.cancel();
|
||||
_sub = null;
|
||||
});
|
||||
return const UserLocation();
|
||||
}
|
||||
|
||||
/// Запросить текущую позицию. Первый вызов проверяет пермишены
|
||||
/// и отдаёт lastKnown мгновенно (если есть).
|
||||
Future<void> fetch() async {
|
||||
if (state.hasPosition) return;
|
||||
|
||||
final err = await _ensurePermission();
|
||||
if (err != null) {
|
||||
state = UserLocation(error: err);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final last = await Geolocator.getLastKnownPosition();
|
||||
if (last != null) {
|
||||
state = UserLocation(position: last);
|
||||
return;
|
||||
}
|
||||
|
||||
final pos = await Geolocator.getCurrentPosition(
|
||||
locationSettings: const LocationSettings(
|
||||
accuracy: LocationAccuracy.low,
|
||||
timeLimit: Duration(seconds: 10),
|
||||
),
|
||||
);
|
||||
state = UserLocation(position: pos);
|
||||
} catch (e) {
|
||||
state = UserLocation(error: 'Ошибка: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Начать непрерывное отслеживание. Вызывать из initState экрана.
|
||||
/// Ref-counted: несколько экранов могут вызвать startWatching,
|
||||
/// стрим остановится только когда все вызовут stopWatching.
|
||||
Future<void> startWatching() async {
|
||||
_watchers++;
|
||||
if (_sub != null) return;
|
||||
|
||||
final err = await _ensurePermission();
|
||||
if (err != null) {
|
||||
state = UserLocation(error: err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.hasPosition) {
|
||||
try {
|
||||
final last = await Geolocator.getLastKnownPosition();
|
||||
if (last != null) {
|
||||
state = UserLocation(position: last);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
const settings = LocationSettings(
|
||||
accuracy: LocationAccuracy.low,
|
||||
distanceFilter: 20,
|
||||
);
|
||||
|
||||
_sub = Geolocator.getPositionStream(locationSettings: settings).listen(
|
||||
(pos) => state = UserLocation(position: pos),
|
||||
onError: (e) {
|
||||
debugPrint('Ошибка стрима геолокации: $e');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Остановить отслеживание. Вызывать из dispose экрана.
|
||||
void stopWatching() {
|
||||
_watchers = (_watchers - 1).clamp(0, 999);
|
||||
if (_watchers == 0) {
|
||||
_sub?.cancel();
|
||||
_sub = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Проверить сервис и пермишены. Возвращает null если всё ок,
|
||||
/// иначе строку с причиной ошибки.
|
||||
Future<String?> _ensurePermission() async {
|
||||
if (!await Geolocator.isLocationServiceEnabled()) {
|
||||
return 'Геолокация выключена';
|
||||
}
|
||||
|
||||
var perm = await Geolocator.checkPermission();
|
||||
if (perm == LocationPermission.denied) {
|
||||
perm = await Geolocator.requestPermission();
|
||||
}
|
||||
if (perm == LocationPermission.denied) {
|
||||
return 'Нет разрешения';
|
||||
}
|
||||
if (perm == LocationPermission.deniedForever) {
|
||||
return 'Разрешение запрещено навсегда';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
double calculateDistanceKm(double lat1, double lon1, double lat2, double lon2) {
|
||||
const earthRadiusKm = 6371.0;
|
||||
final dLat = _degToRad(lat2 - lat1);
|
||||
final dLon = _degToRad(lon2 - lon1);
|
||||
final a =
|
||||
math.sin(dLat / 2) * math.sin(dLat / 2) +
|
||||
math.cos(_degToRad(lat1)) *
|
||||
math.cos(_degToRad(lat2)) *
|
||||
math.sin(dLon / 2) *
|
||||
math.sin(dLon / 2);
|
||||
final c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a));
|
||||
return earthRadiusKm * c;
|
||||
}
|
||||
|
||||
double _degToRad(double deg) => deg * (math.pi / 180);
|
||||
|
||||
/// Форматирование расстояния в человекочитаемый вид
|
||||
String formatDistance(double km) {
|
||||
if (km < 1.0) {
|
||||
return '${(km * 1000).round()} м';
|
||||
} else if (km < 10.0) {
|
||||
return '${km.toStringAsFixed(1)} км';
|
||||
} else {
|
||||
return '${km.round()} км';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user