ViewModel class abstract
Base class for ViewModels in the MVVM pattern.
ViewModel manages the business logic for the UI layer. It provides lifecycle management, automatic disposal of LiveData and other ChangeNotifier objects through DataScope, and built-in loading state management.
Key features:
- Methods
mutableandregisterfor creating observable data - Automatic disposal of all registered LiveData instances
- Built-in isLoading for tracking long-running operations
- Reacts to the UI lifecycle with
onActiveandonInactivecallbacks, which are invoked when the associated view becomes visible or is hidden.
Example:
class CounterViewModel extends ViewModel {
final _counter = mutable(0);
LiveData<int> get counter => _counter;
void increment() {
_counter.value++;
}
@override
void onActive() {
// Called when the view becomes active
}
}
See also:
- ViewState, for connecting ViewModels to widgets
- LiveData and MutableLiveData, for observable data
- DataScope, for managing LiveData lifecycle
Constructors
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- isActive ↔ bool
-
Whether this ViewModel is currently active.
getter/setter pairinherited
-
isLoading
→ LiveData<
bool> -
Observable flag indicating if a long-running action is in progress.
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- scope → DataScope
-
Scope for managing the lifecycle of LiveData instances.
finalinherited
Methods
-
beginLoading(
) → void - Marks the start of a long-running action.
-
completeLoading(
) → void - Marks the end of a long-running action.
-
dispose(
) → void -
inherited
-
ensureActive(
) → Future -
Waits until the ViewModel becomes active.
inherited
-
executeAsync<
T> (Future< T> action()) → Future<T> - Executes an asynchronous action while managing the loading state.
-
mutable<
T> (T value) → MutableLiveData< T> -
Creates a MutableLiveData and registers it in the ViewModel's scope.
inherited
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
onActive(
) → void -
Called when the associated view becomes active (visible).
inherited
-
onInactive(
) → void -
Called when the associated view becomes inactive (hidden).
inherited
-
register<
T extends LiveData> (T value) → T -
Registers an existing LiveData in the ViewModel's scope.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited