0
0
Fluttermobile~10 mins

MVVM pattern in Flutter - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a ViewModel class in Flutter.

Flutter
class CounterViewModel extends ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count[1];
    notifyListeners();
  }
}
Drag options to blanks, or click blank then click option'
A-= 1
B+= 1
C*= 1
D/= 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' decreases the count instead of increasing it.
Using '*=' or '/=' does not increment the count properly.
2fill in blank
medium

Complete the code to notify listeners when the count changes in the ViewModel.

Flutter
void increment() {
  _count += 1;
  [1]();
}
Drag options to blanks, or click blank then click option'
AnotifyListeners
BupdateUI
Crefresh
DsetState
Attempts:
3 left
💡 Hint
Common Mistakes
Using setState inside ViewModel is incorrect; setState is for Widgets.
Using updateUI or refresh are not valid ChangeNotifier methods.
3fill in blank
hard

Fix the error in the View code to listen to the ViewModel changes.

Flutter
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]');
        },
      ),
    );
  }
}
Drag options to blanks, or click blank then click option'
AnotifyListeners
B_count
Cincrement
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using the private variable '_count' directly causes an error.
Using 'increment' or 'notifyListeners' in the Text widget is incorrect.
4fill in blank
hard

Fill both blanks to create a button that calls the ViewModel's increment method when pressed.

Flutter
ElevatedButton(
  onPressed: [1],
  child: Text([2]),
)
Drag options to blanks, or click blank then click option'
AviewModel.increment
BviewModel.increment()
C'Increment'
D'Add'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the function with parentheses in onPressed causes it to run immediately.
Using 'Add' instead of 'Increment' may confuse the user.
5fill in blank
hard

Fill all three blanks to define a simple ViewModel with a private count, a getter, and an increment method.

Flutter
class CounterViewModel extends ChangeNotifier {
  int [1] = 0;

  int get [2] => [3];

  void increment() {
    _count += 1;
    notifyListeners();
  }
}
Drag options to blanks, or click blank then click option'
A_count
Bcount
Dtotal
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the private variable without underscore breaks encapsulation.
Getter returning a wrong variable name causes errors.