74 lines
2.2 KiB
Dart
74 lines
2.2 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter/widgets.dart';
|
|
import 'package:mc_gallery/features/core/services/logging_service.dart';
|
|
import 'package:mc_gallery/l10n/generated/l10n.dart';
|
|
|
|
import '../data/enums/view_model_state.dart';
|
|
|
|
abstract class BaseViewModel<E extends Object?> extends ChangeNotifier {
|
|
final ValueNotifier<bool> _isInitialised = ValueNotifier(false);
|
|
ValueListenable<bool> get isInitialised => _isInitialised;
|
|
|
|
final ValueNotifier<bool> _isBusy = ValueNotifier(false);
|
|
ValueListenable<bool> get isBusy => _isBusy;
|
|
|
|
final ValueNotifier<bool> _hasError = ValueNotifier(false);
|
|
ValueListenable<bool> get hasError => _hasError;
|
|
final ValueNotifier<ViewModelState> _state = ValueNotifier(ViewModelState.isInitialising);
|
|
ValueListenable<ViewModelState> get state => _state;
|
|
|
|
final LoggingService _loggingService = LoggingService.locate;
|
|
|
|
String? _errorMessage;
|
|
String get errorMessage => _errorMessage ?? strings.somethingWentWrong;
|
|
|
|
@mustCallSuper
|
|
void initialise(DisposableBuildContext disposableBuildContext, bool Function() mounted,
|
|
[E? arguments]) {
|
|
_mounted = mounted;
|
|
_isInitialised.value = true;
|
|
_state.value = ViewModelState.isInitialised;
|
|
_loggingService.successfulInit(location: runtimeType.runtimeType.toString());
|
|
}
|
|
|
|
void setBusy(bool isBusy) {
|
|
_isBusy.value = isBusy;
|
|
if (isBusy) {
|
|
_state.value = ViewModelState.isBusy;
|
|
} else {
|
|
_state.value = ViewModelState.isInitialised;
|
|
}
|
|
}
|
|
|
|
void setError(
|
|
bool hasError, {
|
|
String? message,
|
|
}) {
|
|
_errorMessage = hasError ? message : null;
|
|
_hasError.value = hasError;
|
|
if (hasError) {
|
|
_state.value = ViewModelState.hasError;
|
|
} else {
|
|
_state.value = ViewModelState.isInitialised;
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
super.dispose();
|
|
_loggingService.successfulDispose(location: runtimeType.runtimeType.toString());
|
|
}
|
|
|
|
late final bool Function() _mounted;
|
|
void ifMounted(VoidCallback voidCallback) {
|
|
if (_mounted()) {
|
|
voidCallback();
|
|
}
|
|
}
|
|
|
|
final Strings strings = Strings.current;
|
|
|
|
double width(BuildContext context) => MediaQuery.of(context).size.width;
|
|
double height(BuildContext context) => MediaQuery.of(context).size.height;
|
|
}
|