Junior — Middle
What methods can be used to track updates within a component when using the MVVM pattern?
sobes.tech AI
Answer from AI
In the MVVM pattern, there are several approaches to track updates within a component:
-
ChangeNotifier and ValueNotifier: The ViewModel class inherits from ChangeNotifier and calls notifyListeners() when data changes. The View subscribes to these notifications and updates the UI.
-
Streams and StreamBuilder: The ViewModel provides a data stream (Stream), which the UI subscribes to via StreamBuilder, automatically updating with new events.
-
Provider: A popular package for state management that uses ChangeNotifier or other mechanisms to notify listeners.
Example with ChangeNotifier:
class CounterViewModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
// In UI:
// ChangeNotifierProvider(
// create: (_) => CounterViewModel(),
// child: Consumer<CounterViewModel>(
// builder: (context, model, child) => Text('Count: \\${model.count}'),
// ),
// )
Thus, when the state of the ViewModel changes, the UI automatically updates.