Complete the code to declare a ViewModel class in Flutter.
class CounterViewModel extends ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count[1]; notifyListeners(); } }
The increment method should add 1 to the _count variable using the += operator.
Complete the code to notify listeners when the count changes in the ViewModel.
void increment() {
_count += 1;
[1]();
}In Flutter's ChangeNotifier, notifyListeners() tells the UI to update when data changes.
Fix the error in the View code to listen to the ViewModel changes.
class CounterView extends StatelessWidget { final CounterViewModel viewModel; CounterView({required this.viewModel}); @override Widget build(BuildContext context) { return ChangeNotifierProvider.value( value: viewModel, child: Consumer<CounterViewModel>( builder: (context, model, child) { return Text('Count: ${model.[1]'); }, ), ); } }
The View should access the public getter count to display the current count.
Fill both blanks to create a button that calls the ViewModel's increment method when pressed.
ElevatedButton( onPressed: [1], child: Text([2]), )
The onPressed expects a function reference without parentheses, and the button label should be 'Increment'.
Fill all three blanks to define a simple ViewModel with a private count, a getter, and an increment method.
class CounterViewModel extends ChangeNotifier { int [1] = 0; int get [2] => [3]; void increment() { _count += 1; notifyListeners(); } }
The private variable is named _count. The getter is count which returns _count.