refactor(legacy-settings): migrate battery to AsyncNotifier

This commit is contained in:
2026-04-22 00:44:35 +02:00
parent 3b57d0e70d
commit 2eee3489cd
7 changed files with 240 additions and 454 deletions

View File

@@ -1,115 +1,104 @@
import 'package:design_system/design_system.dart';
import 'package:legacy_theme/legacy_theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:legacy_device_state/legacy_device_state.dart';
import 'package:legacy_theme/legacy_theme.dart';
import 'package:legacy_ui/legacy_ui.dart';
import 'package:settings/src/features/battery/presentation/providers/battery_controller.dart';
import 'package:sf_localizations/sf_localizations.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:utils/utils.dart';
import 'state/battery_view_model.dart';
class BatteryScreen extends ConsumerWidget {
const BatteryScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen(batteryControllerProvider, (prev, next) async {
next.showErrorOn(context);
if (prev != null &&
prev.isLoading &&
!next.isLoading &&
!next.hasError) {
await showSuccessDialog(context, I18n.deviceUpdatedSuccess);
}
});
final primaryColor = context.sfColors.legacyPrimary;
final state = ref.watch(batteryViewModelProvider);
final vm = ref.read(batteryViewModelProvider.notifier);
ref.listen(batteryViewModelProvider.select((s) => s.errorEvent), (
previous,
next,
) {
if (next != null) {
showTopSnackbar(
context,
message: context.translate(I18n.errorBatteryNightMode),
type: MessageType.error,
);
}
});
ref.listen(batteryViewModelProvider.select((s) => s.saveSuccess), (
previous,
next,
) {
if (next && !(previous ?? false)) {
showTopSnackbar(
context,
message: context.translate(I18n.batteryNightModeUpdated),
type: MessageType.success,
);
}
});
final device = ref.watch(selectedDeviceProvider).value;
final nightMode = device?.settings.nightMode ?? false;
final isSaving = ref.watch(
batteryControllerProvider.select((s) => s.isLoading),
);
return LegacyPageLayout(
title: context.translate(I18n.batteryNightSaving),
body: state.isLoading
? const Center(child: CircularProgressIndicator())
: Padding(
padding: EdgeInsets.symmetric(
horizontal: SizeUtils.getByScreen(small: 24, big: 22),
body: Padding(
padding: EdgeInsets.symmetric(
horizontal: SizeUtils.getByScreen(small: 24, big: 22),
),
child: Column(
children: [
SizedBox(height: SizeUtils.getByScreen(small: 40, big: 36)),
Icon(
Icons.nightlight_round,
size: SizeUtils.getByScreen(small: 120, big: 110),
color: primaryColor,
),
SizedBox(height: SizeUtils.getByScreen(small: 60, big: 50)),
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.outlineVariant,
borderRadius: BorderRadius.circular(16),
),
child: Column(
child: Row(
children: [
SizedBox(height: SizeUtils.getByScreen(small: 40, big: 36)),
Icon(
Icons.nightlight_round,
size: SizeUtils.getByScreen(small: 120, big: 110),
color: primaryColor,
),
SizedBox(height: SizeUtils.getByScreen(small: 60, big: 50)),
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.outlineVariant,
borderRadius: BorderRadius.circular(16),
),
child: Row(
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
context.translate(I18n.batteryNightModeTitle),
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 8),
Text(
context.translate(
I18n.batteryNightModeDescription,
),
style: TextStyle(
fontSize: 13,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
Text(
context.translate(I18n.batteryNightModeTitle),
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 12),
Switch.adaptive(
value: state.nightMode,
activeTrackColor: primaryColor,
onChanged: state.isSaving
? null
: (value) async {
if (!await guardDeviceCommand(context, ref)) return;
vm.toggleNightMode(value);
},
const SizedBox(height: 8),
Text(
context.translate(I18n.batteryNightModeDescription),
style: TextStyle(
fontSize: 13,
color: Theme.of(context)
.colorScheme
.onSurfaceVariant,
),
),
],
),
),
const SizedBox(width: 12),
Switch.adaptive(
value: nightMode,
activeTrackColor: primaryColor,
onChanged: (isSaving || device == null)
? null
: (value) async {
if (!await guardDeviceCommand(context, ref)) {
return;
}
if (!context.mounted) return;
ref
.read(batteryControllerProvider.notifier)
.toggleNightMode(device: device, value: value);
},
),
],
),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,33 @@
import 'dart:async';
import 'package:legacy_device_state/legacy_device_state.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_tracking/sf_tracking.dart';
part 'battery_controller.g.dart';
@riverpod
class BatteryController extends _$BatteryController {
@override
FutureOr<void> build() {}
Future<void> toggleNightMode({
required DeviceEntity device,
required bool value,
}) async {
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
final updated = device.settings.copyWith(nightMode: value);
await ref
.read(deviceSettingsUpdateProvider)
.updateDeviceSettings(device: device, updatedSettings: updated);
ref.syncDeviceSettings(device, updated);
unawaited(
ref
.read(sfTrackingProvider)
.legacySettingsBatteryNightModeToggled(value),
);
});
}
}

View File

@@ -0,0 +1,55 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'battery_controller.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BatteryController)
const batteryControllerProvider = BatteryControllerProvider._();
final class BatteryControllerProvider
extends $AsyncNotifierProvider<BatteryController, void> {
const BatteryControllerProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'batteryControllerProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$batteryControllerHash();
@$internal
@override
BatteryController create() => BatteryController();
}
String _$batteryControllerHash() => r'72a3f2f6bc750ae7abc067851327df2a58a1046a';
abstract class _$BatteryController extends $AsyncNotifier<void> {
FutureOr<void> build();
@$mustCallSuper
@override
void runBuild() {
build();
final ref = this.ref as $Ref<AsyncValue<void>, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<void>, void>,
AsyncValue<void>,
Object?,
Object?
>;
element.handleValue(ref, null);
}
}

View File

@@ -1,71 +0,0 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:legacy_device_state/legacy_device_state.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_tracking/sf_tracking.dart';
import 'battery_view_state.dart';
final batteryViewModelProvider =
NotifierProvider.autoDispose<BatteryViewModel, BatteryViewState>(
BatteryViewModel.new,
);
class BatteryViewModel extends Notifier<BatteryViewState> {
late final DeviceSettingsUpdateDatasource _datasource;
late final SfTrackingRepository _tracking;
@override
BatteryViewState build() {
_datasource = ref.read(deviceSettingsUpdateProvider);
_tracking = ref.read(sfTrackingProvider);
Future.microtask(_load);
return const BatteryViewState();
}
void _load() {
final device = ref.read(selectedDeviceProvider).value;
if (device == null) return;
state = state.copyWith(
nightMode: device.settings.nightMode,
isLoading: false,
);
}
Future<void> toggleNightMode(bool value) async {
final device = ref.read(selectedDeviceProvider).value;
if (device == null) return;
state = state.copyWith(
isSaving: true,
errorEvent: null,
saveSuccess: false,
);
try {
final updatedSettings = device.settings.copyWith(nightMode: value);
await _datasource.updateDeviceSettings(
device: device,
updatedSettings: updatedSettings,
);
if (!ref.mounted) return;
ref.syncDeviceSettings(device, updatedSettings);
unawaited(_tracking.legacySettingsBatteryNightModeToggled(value));
state = state.copyWith(
nightMode: value,
isSaving: false,
saveSuccess: true,
);
} catch (e) {
if (!ref.mounted) return;
state = state.copyWith(
isSaving: false,
errorEvent: BatteryErrorEvent.update,
);
}
}
}

View File

@@ -1,16 +0,0 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'battery_view_state.freezed.dart';
enum BatteryErrorEvent { update }
@freezed
abstract class BatteryViewState with _$BatteryViewState {
const factory BatteryViewState({
@Default(false) bool nightMode,
@Default(true) bool isLoading,
@Default(false) bool isSaving,
BatteryErrorEvent? errorEvent,
@Default(false) bool saveSuccess,
}) = _BatteryViewState;
}

View File

@@ -1,283 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'battery_view_state.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$BatteryViewState {
bool get nightMode; bool get isLoading; bool get isSaving; BatteryErrorEvent? get errorEvent; bool get saveSuccess;
/// Create a copy of BatteryViewState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$BatteryViewStateCopyWith<BatteryViewState> get copyWith => _$BatteryViewStateCopyWithImpl<BatteryViewState>(this as BatteryViewState, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is BatteryViewState&&(identical(other.nightMode, nightMode) || other.nightMode == nightMode)&&(identical(other.isLoading, isLoading) || other.isLoading == isLoading)&&(identical(other.isSaving, isSaving) || other.isSaving == isSaving)&&(identical(other.errorEvent, errorEvent) || other.errorEvent == errorEvent)&&(identical(other.saveSuccess, saveSuccess) || other.saveSuccess == saveSuccess));
}
@override
int get hashCode => Object.hash(runtimeType,nightMode,isLoading,isSaving,errorEvent,saveSuccess);
@override
String toString() {
return 'BatteryViewState(nightMode: $nightMode, isLoading: $isLoading, isSaving: $isSaving, errorEvent: $errorEvent, saveSuccess: $saveSuccess)';
}
}
/// @nodoc
abstract mixin class $BatteryViewStateCopyWith<$Res> {
factory $BatteryViewStateCopyWith(BatteryViewState value, $Res Function(BatteryViewState) _then) = _$BatteryViewStateCopyWithImpl;
@useResult
$Res call({
bool nightMode, bool isLoading, bool isSaving, BatteryErrorEvent? errorEvent, bool saveSuccess
});
}
/// @nodoc
class _$BatteryViewStateCopyWithImpl<$Res>
implements $BatteryViewStateCopyWith<$Res> {
_$BatteryViewStateCopyWithImpl(this._self, this._then);
final BatteryViewState _self;
final $Res Function(BatteryViewState) _then;
/// Create a copy of BatteryViewState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? nightMode = null,Object? isLoading = null,Object? isSaving = null,Object? errorEvent = freezed,Object? saveSuccess = null,}) {
return _then(_self.copyWith(
nightMode: null == nightMode ? _self.nightMode : nightMode // ignore: cast_nullable_to_non_nullable
as bool,isLoading: null == isLoading ? _self.isLoading : isLoading // ignore: cast_nullable_to_non_nullable
as bool,isSaving: null == isSaving ? _self.isSaving : isSaving // ignore: cast_nullable_to_non_nullable
as bool,errorEvent: freezed == errorEvent ? _self.errorEvent : errorEvent // ignore: cast_nullable_to_non_nullable
as BatteryErrorEvent?,saveSuccess: null == saveSuccess ? _self.saveSuccess : saveSuccess // ignore: cast_nullable_to_non_nullable
as bool,
));
}
}
/// Adds pattern-matching-related methods to [BatteryViewState].
extension BatteryViewStatePatterns on BatteryViewState {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _BatteryViewState value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _BatteryViewState() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _BatteryViewState value) $default,){
final _that = this;
switch (_that) {
case _BatteryViewState():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _BatteryViewState value)? $default,){
final _that = this;
switch (_that) {
case _BatteryViewState() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool nightMode, bool isLoading, bool isSaving, BatteryErrorEvent? errorEvent, bool saveSuccess)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _BatteryViewState() when $default != null:
return $default(_that.nightMode,_that.isLoading,_that.isSaving,_that.errorEvent,_that.saveSuccess);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool nightMode, bool isLoading, bool isSaving, BatteryErrorEvent? errorEvent, bool saveSuccess) $default,) {final _that = this;
switch (_that) {
case _BatteryViewState():
return $default(_that.nightMode,_that.isLoading,_that.isSaving,_that.errorEvent,_that.saveSuccess);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool nightMode, bool isLoading, bool isSaving, BatteryErrorEvent? errorEvent, bool saveSuccess)? $default,) {final _that = this;
switch (_that) {
case _BatteryViewState() when $default != null:
return $default(_that.nightMode,_that.isLoading,_that.isSaving,_that.errorEvent,_that.saveSuccess);case _:
return null;
}
}
}
/// @nodoc
class _BatteryViewState implements BatteryViewState {
const _BatteryViewState({this.nightMode = false, this.isLoading = true, this.isSaving = false, this.errorEvent, this.saveSuccess = false});
@override@JsonKey() final bool nightMode;
@override@JsonKey() final bool isLoading;
@override@JsonKey() final bool isSaving;
@override final BatteryErrorEvent? errorEvent;
@override@JsonKey() final bool saveSuccess;
/// Create a copy of BatteryViewState
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$BatteryViewStateCopyWith<_BatteryViewState> get copyWith => __$BatteryViewStateCopyWithImpl<_BatteryViewState>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _BatteryViewState&&(identical(other.nightMode, nightMode) || other.nightMode == nightMode)&&(identical(other.isLoading, isLoading) || other.isLoading == isLoading)&&(identical(other.isSaving, isSaving) || other.isSaving == isSaving)&&(identical(other.errorEvent, errorEvent) || other.errorEvent == errorEvent)&&(identical(other.saveSuccess, saveSuccess) || other.saveSuccess == saveSuccess));
}
@override
int get hashCode => Object.hash(runtimeType,nightMode,isLoading,isSaving,errorEvent,saveSuccess);
@override
String toString() {
return 'BatteryViewState(nightMode: $nightMode, isLoading: $isLoading, isSaving: $isSaving, errorEvent: $errorEvent, saveSuccess: $saveSuccess)';
}
}
/// @nodoc
abstract mixin class _$BatteryViewStateCopyWith<$Res> implements $BatteryViewStateCopyWith<$Res> {
factory _$BatteryViewStateCopyWith(_BatteryViewState value, $Res Function(_BatteryViewState) _then) = __$BatteryViewStateCopyWithImpl;
@override @useResult
$Res call({
bool nightMode, bool isLoading, bool isSaving, BatteryErrorEvent? errorEvent, bool saveSuccess
});
}
/// @nodoc
class __$BatteryViewStateCopyWithImpl<$Res>
implements _$BatteryViewStateCopyWith<$Res> {
__$BatteryViewStateCopyWithImpl(this._self, this._then);
final _BatteryViewState _self;
final $Res Function(_BatteryViewState) _then;
/// Create a copy of BatteryViewState
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? nightMode = null,Object? isLoading = null,Object? isSaving = null,Object? errorEvent = freezed,Object? saveSuccess = null,}) {
return _then(_BatteryViewState(
nightMode: null == nightMode ? _self.nightMode : nightMode // ignore: cast_nullable_to_non_nullable
as bool,isLoading: null == isLoading ? _self.isLoading : isLoading // ignore: cast_nullable_to_non_nullable
as bool,isSaving: null == isSaving ? _self.isSaving : isSaving // ignore: cast_nullable_to_non_nullable
as bool,errorEvent: freezed == errorEvent ? _self.errorEvent : errorEvent // ignore: cast_nullable_to_non_nullable
as BatteryErrorEvent?,saveSuccess: null == saveSuccess ? _self.saveSuccess : saveSuccess // ignore: cast_nullable_to_non_nullable
as bool,
));
}
}
// dart format on

View File

@@ -0,0 +1,79 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:legacy_device_state/legacy_device_state.dart';
import 'package:mocktail/mocktail.dart';
import 'package:settings/src/features/battery/presentation/providers/battery_controller.dart';
import 'package:sf_infrastructure/sf_infrastructure.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_shared/testing.dart';
import 'package:sf_tracking/sf_tracking.dart';
class MockDeviceSettingsUpdateDatasource extends Mock
implements DeviceSettingsUpdateDatasource {}
const _device = DeviceEntity(
id: 'device-1',
identificator: 'imei-1',
carrierName: 'Watch',
settings: DeviceSettingsEntity(nightMode: false),
);
void main() {
setUpAll(() {
registerFallbackValue(_device);
registerFallbackValue(const DeviceSettingsEntity());
});
ProviderContainer buildContainer(DeviceSettingsUpdateDatasource ds) {
return makeContainer(
overrides: [
deviceSettingsUpdateProvider.overrideWithValue(ds),
sfTrackingProvider.overrideWithValue(
SfTrackingRepository(clients: const []),
),
],
);
}
group('BatteryController.toggleNightMode', () {
test('transitions to AsyncData when datasource succeeds', () async {
final ds = MockDeviceSettingsUpdateDatasource();
when(
() => ds.updateDeviceSettings(
device: any(named: 'device'),
updatedSettings: any(named: 'updatedSettings'),
),
).thenAnswer((_) async {});
final container = buildContainer(ds);
addTearDown(container.dispose);
await container
.read(batteryControllerProvider.notifier)
.toggleNightMode(device: _device, value: true);
expect(container.read(batteryControllerProvider), isA<AsyncData<void>>());
});
test('exposes AsyncError when datasource fails', () async {
final ds = MockDeviceSettingsUpdateDatasource();
when(
() => ds.updateDeviceSettings(
device: any(named: 'device'),
updatedSettings: any(named: 'updatedSettings'),
),
).thenThrow(const ApiException(message: 'boom', isNetworkError: true));
final container = buildContainer(ds);
addTearDown(container.dispose);
await container
.read(batteryControllerProvider.notifier)
.toggleNightMode(device: _device, value: true);
final state = container.read(batteryControllerProvider);
expect(state, isA<AsyncError<void>>());
expect(state.error, isA<ApiException>());
});
});
}