fbmobile/lib/core/viewmodels/base_model.dart

87 lines
2.1 KiB
Dart
Raw 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 {
static const String STATE_VIEW = 'viewState';
static const String STATE_MESSAGE = 'viewMessage';
2021-02-02 14:33:23 +00:00
final Logger _logger = getLogger();
bool _isDisposed = false;
Map<String, Object?> _stateMap = {STATE_VIEW: ViewState.Idle, STATE_MESSAGE: null};
2021-02-02 14:33:23 +00:00
ViewState? get state => _stateMap[STATE_VIEW] as ViewState?;
2021-05-20 23:33:16 +00:00
String? get stateMessage => _stateMap[STATE_MESSAGE] 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;
}
void setStateBoolValue(String key, bool stateValue) => _setStateValue(key, stateValue);
void setStateIntValue(String key, int? stateValue) => _setStateValue(key, stateValue);
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();
_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) {
_setStateValue(STATE_VIEW, stateView);
}
void setStateMessage(String? stateMessage) {
_setStateValue(STATE_MESSAGE, stateMessage);
}
2021-02-02 14:33:23 +00:00
@override
void dispose() {
super.dispose();
_isDisposed = true;
}
}