fbmobile/lib/core/viewmodels/base_model.dart

95 lines
2.2 KiB
Dart
Raw Permalink Normal View History

2021-02-02 14:33:23 +00:00
import 'package:flutter/widgets.dart';
import 'package:logger/logger.dart';
import '../../core/util/logger.dart';
import '../enums/viewstate.dart';
class BaseModel extends ChangeNotifier {
2023-01-04 20:17:54 +00:00
static const String stateViewKey = 'viewState';
static const String stateMessageKey = 'viewMessage';
2021-02-02 14:33:23 +00:00
final Logger _logger = getLogger();
bool _isDisposed = false;
2023-01-16 00:44:34 +00:00
final Map<String, Object?> _stateMap = {
stateViewKey: ViewState.idle,
stateMessageKey: null
};
2021-02-02 14:33:23 +00:00
2023-01-04 20:17:54 +00:00
ViewState? get state => _stateMap[stateViewKey] as ViewState?;
2021-05-20 23:33:16 +00:00
2023-01-04 20:17:54 +00:00
String? get stateMessage => _stateMap[stateMessageKey] as String?;
2021-02-02 14:33:23 +00:00
bool getStateValueAsBoolean(String key) {
if (_stateMap.containsKey(key) && _stateMap[key] is bool) {
return _stateMap[key] as bool;
}
return false;
}
String? getStateValueAsString(String key) {
if (_stateMap.containsKey(key) && _stateMap[key] is String) {
return _stateMap[key] as String;
}
return null;
}
int? getStateValueAsInt(String key) {
if (_stateMap.containsKey(key) && _stateMap[key] is int) {
return _stateMap[key] as int;
}
return null;
}
2023-01-16 00:44:34 +00:00
void setStateBoolValue(String key, bool stateValue) =>
_setStateValue(key, stateValue);
2023-01-16 00:44:34 +00:00
void setStateIntValue(String key, int? stateValue) =>
_setStateValue(key, stateValue);
2023-01-16 00:44:34 +00:00
void setStateStringValue(String key, String? stateValue) =>
_setStateValue(key, stateValue);
void _setStateValue(String key, Object? stateValue) {
if (_stateMap.containsKey(key)) {
_stateMap.update(key, (value) => stateValue);
} else {
_stateMap.putIfAbsent(key, () => stateValue);
}
2021-02-02 14:33:23 +00:00
if (!_isDisposed) {
notifyListeners();
2023-01-16 00:44:34 +00:00
_logger
.d("Notified state value update '($key, ${stateValue.toString()})'");
2021-02-02 14:33:23 +00:00
}
}
void removeStateValue(String key) {
_stateMap.remove(key);
2021-02-02 14:33:23 +00:00
if (!_isDisposed) {
notifyListeners();
_logger.d("Notified state removal of '$key'");
2021-02-02 14:33:23 +00:00
}
}
void setStateView(ViewState stateView) {
2023-01-04 20:17:54 +00:00
_setStateValue(stateViewKey, stateView);
}
void setStateMessage(String? stateMessage) {
2023-01-04 20:17:54 +00:00
_setStateValue(stateMessageKey, stateMessage);
}
2021-02-02 14:33:23 +00:00
@override
void dispose() {
_logger.d("Calling dispose");
2021-02-02 14:33:23 +00:00
super.dispose();
_isDisposed = true;
}
}