Sobes.tech
Junior — Middle

Can you tell how the MVVM architectural pattern is implemented in applications?

sobes.tech AI

Answer from AI

The MVVM (Model-View-ViewModel) architectural pattern in applications divides logic into three components:

  • Model — responsible for data and business logic.
  • View — displays the interface and interacts with the user.
  • ViewModel — acts as an intermediary between Model and View, containing presentation logic and state.

In Flutter, MVVM is implemented as follows:

  1. Model — classes that describe data and methods to work with it (e.g., fetching from an API).

  2. ViewModel — a class that contains state and methods to manage data, and notifies the View of changes (often using ChangeNotifier or Stream).

  3. View — Flutter widgets that subscribe to changes in the ViewModel and update when the state changes.

Example of a simple ViewModel using ChangeNotifier:

class CounterViewModel extends ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
    notifyListeners();
  }
}

In the widget:

class CounterView extends StatelessWidget {
  final CounterViewModel viewModel;

  CounterView(this.viewModel);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => viewModel,
      child: Consumer<CounterViewModel>(
        builder: (context, vm, child) => Column(
          children: [
            Text('Count: \\${vm.count}'),
            ElevatedButton(
              onPressed: vm.increment,
              child: Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }
}

Thus, the ViewModel manages state and logic, the View displays the UI and reacts to changes, and the Model stores data.