refactor(legacy-settings): migrate alerts to AsyncNotifier
This commit is contained in:
@@ -1,90 +1,86 @@
|
||||
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/alerts/presentation/providers/alerts_controller.dart';
|
||||
import 'package:settings/src/features/alerts/presentation/providers/alerts_selection_provider.dart';
|
||||
import 'package:sf_localizations/sf_localizations.dart';
|
||||
import 'package:sf_shared/sf_shared.dart';
|
||||
import 'package:utils/utils.dart';
|
||||
|
||||
import 'state/alerts_view_model.dart';
|
||||
|
||||
class AlertsScreen extends ConsumerWidget {
|
||||
const AlertsScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final state = ref.watch(alertsViewModelProvider);
|
||||
final vm = ref.read(alertsViewModelProvider.notifier);
|
||||
|
||||
ref.listen(alertsViewModelProvider.select((s) => s.errorEvent), (
|
||||
previous,
|
||||
next,
|
||||
) {
|
||||
if (next != null) {
|
||||
showTopSnackbar(
|
||||
context,
|
||||
message: context.translate(I18n.errorAlertUpdate),
|
||||
type: MessageType.error,
|
||||
);
|
||||
ref.listen(alertsControllerProvider, (prev, next) async {
|
||||
next.showErrorOn(context);
|
||||
if (prev != null &&
|
||||
prev.isLoading &&
|
||||
!next.isLoading &&
|
||||
!next.hasError) {
|
||||
ref.read(alertsSelectionProvider.notifier).clear();
|
||||
await showSuccessDialog(context, I18n.deviceUpdatedSuccess);
|
||||
if (context.mounted) Navigator.of(context).pop();
|
||||
}
|
||||
});
|
||||
|
||||
ref.listen(alertsViewModelProvider.select((s) => s.saveSuccess), (
|
||||
previous,
|
||||
next,
|
||||
) {
|
||||
if (next && !(previous ?? false)) {
|
||||
showTopSnackbar(
|
||||
context,
|
||||
message: context.translate(I18n.alertsUpdated),
|
||||
type: MessageType.success,
|
||||
);
|
||||
}
|
||||
});
|
||||
final device = ref.watch(selectedDeviceProvider).value;
|
||||
final availableAlerts = device?.capabilities?.alerts?.types ?? const [];
|
||||
final currentAlerts = device?.settings.alerts ?? const <String>[];
|
||||
final activeAlerts =
|
||||
ref.watch(alertsSelectionProvider) ?? currentAlerts;
|
||||
final isSaving =
|
||||
ref.watch(alertsControllerProvider.select((s) => s.isLoading));
|
||||
|
||||
return LegacyPageLayout(
|
||||
title: context.translate(I18n.alerts),
|
||||
body: state.isLoading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: SingleChildScrollView(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: SizeUtils.getByScreen(small: 16, big: 14),
|
||||
vertical: SizeUtils.getByScreen(small: 16, big: 14),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
context.translate(I18n.alertsDescription),
|
||||
style: TextStyle(
|
||||
fontSize: SizeUtils.getByScreen(small: 14, big: 15),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurface.withAlpha(178),
|
||||
),
|
||||
),
|
||||
SizedBox(height: SizeUtils.getByScreen(small: 16, big: 14)),
|
||||
...state.availableAlerts.map(
|
||||
(alert) => _AlertToggle(
|
||||
label: _alertLabel(context, alert),
|
||||
isActive: state.activeAlerts.contains(alert),
|
||||
onChanged: (_) => vm.toggleAlert(alert),
|
||||
),
|
||||
),
|
||||
],
|
||||
body: SingleChildScrollView(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: SizeUtils.getByScreen(small: 16, big: 14),
|
||||
vertical: SizeUtils.getByScreen(small: 16, big: 14),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
context.translate(I18n.alertsDescription),
|
||||
style: TextStyle(
|
||||
fontSize: SizeUtils.getByScreen(small: 14, big: 15),
|
||||
color:
|
||||
Theme.of(context).colorScheme.onSurface.withAlpha(178),
|
||||
),
|
||||
),
|
||||
SizedBox(height: SizeUtils.getByScreen(small: 16, big: 14)),
|
||||
...availableAlerts.map(
|
||||
(alert) => _AlertToggle(
|
||||
label: _alertLabel(context, alert),
|
||||
isActive: activeAlerts.contains(alert),
|
||||
onChanged: (_) => ref
|
||||
.read(alertsSelectionProvider.notifier)
|
||||
.toggle(current: currentAlerts, alert: alert),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
footer: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10),
|
||||
child: PrimaryButton(
|
||||
onPressed: state.isSaving
|
||||
onPressed: isSaving
|
||||
? null
|
||||
: () async {
|
||||
if (device == null) return;
|
||||
if (!await guardDeviceCommand(context, ref)) return;
|
||||
vm.save();
|
||||
if (!context.mounted) return;
|
||||
ref.read(alertsControllerProvider.notifier).save(
|
||||
device: device,
|
||||
alerts: activeAlerts,
|
||||
);
|
||||
},
|
||||
text: state.isSaving ? '...' : context.translate(I18n.save),
|
||||
text: isSaving ? '...' : context.translate(I18n.save),
|
||||
color: context.sfColors.legacyPrimary,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
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 'alerts_controller.g.dart';
|
||||
|
||||
@riverpod
|
||||
class AlertsController extends _$AlertsController {
|
||||
@override
|
||||
FutureOr<void> build() {}
|
||||
|
||||
Future<void> save({
|
||||
required DeviceEntity device,
|
||||
required List<String> alerts,
|
||||
}) async {
|
||||
state = const AsyncLoading();
|
||||
state = await AsyncValue.guard(() async {
|
||||
final updated = device.settings.copyWith(alerts: alerts);
|
||||
await ref
|
||||
.read(deviceSettingsUpdateProvider)
|
||||
.updateDeviceSettings(device: device, updatedSettings: updated);
|
||||
ref.syncDeviceSettings(device, updated);
|
||||
|
||||
final joined = alerts.join(',');
|
||||
final truncated = joined.length > 100 ? joined.substring(0, 100) : joined;
|
||||
unawaited(
|
||||
ref.read(sfTrackingProvider).legacySettingsAlertsConfigured(
|
||||
alertCount: alerts.length,
|
||||
alertsEnabled: truncated,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'alerts_controller.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(AlertsController)
|
||||
const alertsControllerProvider = AlertsControllerProvider._();
|
||||
|
||||
final class AlertsControllerProvider
|
||||
extends $AsyncNotifierProvider<AlertsController, void> {
|
||||
const AlertsControllerProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'alertsControllerProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$alertsControllerHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
AlertsController create() => AlertsController();
|
||||
}
|
||||
|
||||
String _$alertsControllerHash() => r'8f843336ac3998769a35047f027e49af4a9ad7de';
|
||||
|
||||
abstract class _$AlertsController 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'alerts_selection_provider.g.dart';
|
||||
|
||||
@riverpod
|
||||
class AlertsSelection extends _$AlertsSelection {
|
||||
@override
|
||||
List<String>? build() => null;
|
||||
|
||||
void toggle({required List<String> current, required String alert}) {
|
||||
final base = state ?? current;
|
||||
if (base.contains(alert)) {
|
||||
state = base.where((a) => a != alert).toList();
|
||||
} else {
|
||||
state = [...base, alert];
|
||||
}
|
||||
}
|
||||
|
||||
void clear() => state = null;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'alerts_selection_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(AlertsSelection)
|
||||
const alertsSelectionProvider = AlertsSelectionProvider._();
|
||||
|
||||
final class AlertsSelectionProvider
|
||||
extends $NotifierProvider<AlertsSelection, List<String>?> {
|
||||
const AlertsSelectionProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'alertsSelectionProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$alertsSelectionHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
AlertsSelection create() => AlertsSelection();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(List<String>? value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<List<String>?>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$alertsSelectionHash() => r'4c37291a55c96514afc5a5bb1cb72e96631d6beb';
|
||||
|
||||
abstract class _$AlertsSelection extends $Notifier<List<String>?> {
|
||||
List<String>? build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final created = build();
|
||||
final ref = this.ref as $Ref<List<String>?, List<String>?>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<List<String>?, List<String>?>,
|
||||
List<String>?,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleValue(ref, created);
|
||||
}
|
||||
}
|
||||
@@ -1,92 +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 'alerts_view_state.dart';
|
||||
|
||||
final alertsViewModelProvider =
|
||||
NotifierProvider.autoDispose<AlertsViewModel, AlertsViewState>(
|
||||
AlertsViewModel.new,
|
||||
);
|
||||
|
||||
class AlertsViewModel extends Notifier<AlertsViewState> {
|
||||
late final DeviceSettingsUpdateDatasource _datasource;
|
||||
late final SfTrackingRepository _tracking;
|
||||
|
||||
@override
|
||||
AlertsViewState build() {
|
||||
_datasource = ref.read(deviceSettingsUpdateProvider);
|
||||
_tracking = ref.read(sfTrackingProvider);
|
||||
Future.microtask(_load);
|
||||
return const AlertsViewState();
|
||||
}
|
||||
|
||||
void _load() {
|
||||
final device = ref.read(selectedDeviceProvider).value;
|
||||
if (device == null) return;
|
||||
|
||||
final available = device.capabilities?.alerts?.types ?? [];
|
||||
final active = device.settings.alerts;
|
||||
|
||||
state = state.copyWith(
|
||||
availableAlerts: available,
|
||||
activeAlerts: active,
|
||||
isLoading: false,
|
||||
);
|
||||
}
|
||||
|
||||
void toggleAlert(String alert) {
|
||||
final current = List<String>.from(state.activeAlerts);
|
||||
if (current.contains(alert)) {
|
||||
current.remove(alert);
|
||||
} else {
|
||||
current.add(alert);
|
||||
}
|
||||
state = state.copyWith(activeAlerts: current);
|
||||
}
|
||||
|
||||
Future<void> save() 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(
|
||||
alerts: state.activeAlerts,
|
||||
);
|
||||
await _datasource.updateDeviceSettings(
|
||||
device: device,
|
||||
updatedSettings: updatedSettings,
|
||||
);
|
||||
if (!ref.mounted) return;
|
||||
ref.syncDeviceSettings(device, updatedSettings);
|
||||
|
||||
final alertsJoined = state.activeAlerts.join(',');
|
||||
final truncated = alertsJoined.length > 100
|
||||
? alertsJoined.substring(0, 100)
|
||||
: alertsJoined;
|
||||
unawaited(
|
||||
_tracking.legacySettingsAlertsConfigured(
|
||||
alertCount: state.activeAlerts.length,
|
||||
alertsEnabled: truncated,
|
||||
),
|
||||
);
|
||||
|
||||
state = state.copyWith(isSaving: false, saveSuccess: true);
|
||||
} catch (e) {
|
||||
if (!ref.mounted) return;
|
||||
state = state.copyWith(
|
||||
isSaving: false,
|
||||
errorEvent: AlertsErrorEvent.update,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'alerts_view_state.freezed.dart';
|
||||
|
||||
enum AlertsErrorEvent { load, update }
|
||||
|
||||
@freezed
|
||||
abstract class AlertsViewState with _$AlertsViewState {
|
||||
const factory AlertsViewState({
|
||||
@Default([]) List<String> availableAlerts,
|
||||
@Default([]) List<String> activeAlerts,
|
||||
@Default(true) bool isLoading,
|
||||
@Default(false) bool isSaving,
|
||||
AlertsErrorEvent? errorEvent,
|
||||
@Default(false) bool saveSuccess,
|
||||
}) = _AlertsViewState;
|
||||
}
|
||||
@@ -1,298 +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 'alerts_view_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// dart format off
|
||||
T _$identity<T>(T value) => value;
|
||||
/// @nodoc
|
||||
mixin _$AlertsViewState {
|
||||
|
||||
List<String> get availableAlerts; List<String> get activeAlerts; bool get isLoading; bool get isSaving; AlertsErrorEvent? get errorEvent; bool get saveSuccess;
|
||||
/// Create a copy of AlertsViewState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$AlertsViewStateCopyWith<AlertsViewState> get copyWith => _$AlertsViewStateCopyWithImpl<AlertsViewState>(this as AlertsViewState, _$identity);
|
||||
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is AlertsViewState&&const DeepCollectionEquality().equals(other.availableAlerts, availableAlerts)&&const DeepCollectionEquality().equals(other.activeAlerts, activeAlerts)&&(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,const DeepCollectionEquality().hash(availableAlerts),const DeepCollectionEquality().hash(activeAlerts),isLoading,isSaving,errorEvent,saveSuccess);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AlertsViewState(availableAlerts: $availableAlerts, activeAlerts: $activeAlerts, isLoading: $isLoading, isSaving: $isSaving, errorEvent: $errorEvent, saveSuccess: $saveSuccess)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $AlertsViewStateCopyWith<$Res> {
|
||||
factory $AlertsViewStateCopyWith(AlertsViewState value, $Res Function(AlertsViewState) _then) = _$AlertsViewStateCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
List<String> availableAlerts, List<String> activeAlerts, bool isLoading, bool isSaving, AlertsErrorEvent? errorEvent, bool saveSuccess
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class _$AlertsViewStateCopyWithImpl<$Res>
|
||||
implements $AlertsViewStateCopyWith<$Res> {
|
||||
_$AlertsViewStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final AlertsViewState _self;
|
||||
final $Res Function(AlertsViewState) _then;
|
||||
|
||||
/// Create a copy of AlertsViewState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? availableAlerts = null,Object? activeAlerts = null,Object? isLoading = null,Object? isSaving = null,Object? errorEvent = freezed,Object? saveSuccess = null,}) {
|
||||
return _then(_self.copyWith(
|
||||
availableAlerts: null == availableAlerts ? _self.availableAlerts : availableAlerts // ignore: cast_nullable_to_non_nullable
|
||||
as List<String>,activeAlerts: null == activeAlerts ? _self.activeAlerts : activeAlerts // ignore: cast_nullable_to_non_nullable
|
||||
as List<String>,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 AlertsErrorEvent?,saveSuccess: null == saveSuccess ? _self.saveSuccess : saveSuccess // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// Adds pattern-matching-related methods to [AlertsViewState].
|
||||
extension AlertsViewStatePatterns on AlertsViewState {
|
||||
/// 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( _AlertsViewState value)? $default,{required TResult orElse(),}){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AlertsViewState() 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( _AlertsViewState value) $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AlertsViewState():
|
||||
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( _AlertsViewState value)? $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AlertsViewState() 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( List<String> availableAlerts, List<String> activeAlerts, bool isLoading, bool isSaving, AlertsErrorEvent? errorEvent, bool saveSuccess)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
switch (_that) {
|
||||
case _AlertsViewState() when $default != null:
|
||||
return $default(_that.availableAlerts,_that.activeAlerts,_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( List<String> availableAlerts, List<String> activeAlerts, bool isLoading, bool isSaving, AlertsErrorEvent? errorEvent, bool saveSuccess) $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _AlertsViewState():
|
||||
return $default(_that.availableAlerts,_that.activeAlerts,_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( List<String> availableAlerts, List<String> activeAlerts, bool isLoading, bool isSaving, AlertsErrorEvent? errorEvent, bool saveSuccess)? $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _AlertsViewState() when $default != null:
|
||||
return $default(_that.availableAlerts,_that.activeAlerts,_that.isLoading,_that.isSaving,_that.errorEvent,_that.saveSuccess);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
|
||||
class _AlertsViewState implements AlertsViewState {
|
||||
const _AlertsViewState({final List<String> availableAlerts = const [], final List<String> activeAlerts = const [], this.isLoading = true, this.isSaving = false, this.errorEvent, this.saveSuccess = false}): _availableAlerts = availableAlerts,_activeAlerts = activeAlerts;
|
||||
|
||||
|
||||
final List<String> _availableAlerts;
|
||||
@override@JsonKey() List<String> get availableAlerts {
|
||||
if (_availableAlerts is EqualUnmodifiableListView) return _availableAlerts;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_availableAlerts);
|
||||
}
|
||||
|
||||
final List<String> _activeAlerts;
|
||||
@override@JsonKey() List<String> get activeAlerts {
|
||||
if (_activeAlerts is EqualUnmodifiableListView) return _activeAlerts;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_activeAlerts);
|
||||
}
|
||||
|
||||
@override@JsonKey() final bool isLoading;
|
||||
@override@JsonKey() final bool isSaving;
|
||||
@override final AlertsErrorEvent? errorEvent;
|
||||
@override@JsonKey() final bool saveSuccess;
|
||||
|
||||
/// Create a copy of AlertsViewState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$AlertsViewStateCopyWith<_AlertsViewState> get copyWith => __$AlertsViewStateCopyWithImpl<_AlertsViewState>(this, _$identity);
|
||||
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AlertsViewState&&const DeepCollectionEquality().equals(other._availableAlerts, _availableAlerts)&&const DeepCollectionEquality().equals(other._activeAlerts, _activeAlerts)&&(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,const DeepCollectionEquality().hash(_availableAlerts),const DeepCollectionEquality().hash(_activeAlerts),isLoading,isSaving,errorEvent,saveSuccess);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AlertsViewState(availableAlerts: $availableAlerts, activeAlerts: $activeAlerts, isLoading: $isLoading, isSaving: $isSaving, errorEvent: $errorEvent, saveSuccess: $saveSuccess)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$AlertsViewStateCopyWith<$Res> implements $AlertsViewStateCopyWith<$Res> {
|
||||
factory _$AlertsViewStateCopyWith(_AlertsViewState value, $Res Function(_AlertsViewState) _then) = __$AlertsViewStateCopyWithImpl;
|
||||
@override @useResult
|
||||
$Res call({
|
||||
List<String> availableAlerts, List<String> activeAlerts, bool isLoading, bool isSaving, AlertsErrorEvent? errorEvent, bool saveSuccess
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class __$AlertsViewStateCopyWithImpl<$Res>
|
||||
implements _$AlertsViewStateCopyWith<$Res> {
|
||||
__$AlertsViewStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _AlertsViewState _self;
|
||||
final $Res Function(_AlertsViewState) _then;
|
||||
|
||||
/// Create a copy of AlertsViewState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? availableAlerts = null,Object? activeAlerts = null,Object? isLoading = null,Object? isSaving = null,Object? errorEvent = freezed,Object? saveSuccess = null,}) {
|
||||
return _then(_AlertsViewState(
|
||||
availableAlerts: null == availableAlerts ? _self._availableAlerts : availableAlerts // ignore: cast_nullable_to_non_nullable
|
||||
as List<String>,activeAlerts: null == activeAlerts ? _self._activeAlerts : activeAlerts // ignore: cast_nullable_to_non_nullable
|
||||
as List<String>,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 AlertsErrorEvent?,saveSuccess: null == saveSuccess ? _self.saveSuccess : saveSuccess // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// dart format on
|
||||
@@ -0,0 +1,87 @@
|
||||
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/alerts/presentation/providers/alerts_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(alerts: ['sos']),
|
||||
);
|
||||
|
||||
void main() {
|
||||
setUpAll(() {
|
||||
registerFallbackValue(_device);
|
||||
registerFallbackValue(const DeviceSettingsEntity());
|
||||
});
|
||||
|
||||
ProviderContainer buildContainer(DeviceSettingsUpdateDatasource ds) {
|
||||
return makeContainer(
|
||||
overrides: [
|
||||
deviceSettingsUpdateProvider.overrideWithValue(ds),
|
||||
sfTrackingProvider.overrideWithValue(
|
||||
SfTrackingRepository(clients: const []),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
group('AlertsController.save', () {
|
||||
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(alertsControllerProvider.notifier)
|
||||
.save(device: _device, alerts: const ['sos', 'falldown']);
|
||||
|
||||
expect(container.read(alertsControllerProvider), isA<AsyncData<void>>());
|
||||
|
||||
final captured = verify(
|
||||
() => ds.updateDeviceSettings(
|
||||
device: _device,
|
||||
updatedSettings: captureAny(named: 'updatedSettings'),
|
||||
),
|
||||
).captured.single as DeviceSettingsEntity;
|
||||
expect(captured.alerts, ['sos', 'falldown']);
|
||||
});
|
||||
|
||||
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(alertsControllerProvider.notifier)
|
||||
.save(device: _device, alerts: const ['sos']);
|
||||
|
||||
final state = container.read(alertsControllerProvider);
|
||||
expect(state, isA<AsyncError<void>>());
|
||||
expect(state.error, isA<ApiException>());
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:settings/src/features/alerts/presentation/providers/alerts_selection_provider.dart';
|
||||
import 'package:sf_shared/testing.dart';
|
||||
|
||||
void main() {
|
||||
group('AlertsSelection', () {
|
||||
test('defaults to null', () {
|
||||
final container = makeContainer();
|
||||
addTearDown(container.dispose);
|
||||
expect(container.read(alertsSelectionProvider), isNull);
|
||||
});
|
||||
|
||||
test('toggle adds alert when not in current', () {
|
||||
final container = makeContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
container
|
||||
.read(alertsSelectionProvider.notifier)
|
||||
.toggle(current: const ['sos'], alert: 'falldown');
|
||||
|
||||
expect(
|
||||
container.read(alertsSelectionProvider),
|
||||
['sos', 'falldown'],
|
||||
);
|
||||
});
|
||||
|
||||
test('toggle removes alert when already in current', () {
|
||||
final container = makeContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
container
|
||||
.read(alertsSelectionProvider.notifier)
|
||||
.toggle(current: const ['sos', 'falldown'], alert: 'sos');
|
||||
|
||||
expect(container.read(alertsSelectionProvider), ['falldown']);
|
||||
});
|
||||
|
||||
test('clear resets state to null', () {
|
||||
final container = makeContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
container
|
||||
.read(alertsSelectionProvider.notifier)
|
||||
.toggle(current: const [], alert: 'sos');
|
||||
container.read(alertsSelectionProvider.notifier).clear();
|
||||
|
||||
expect(container.read(alertsSelectionProvider), isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user