Sub topic 1
What MVVM means in a Flutter app
Model-View-ViewModel (MVVM) is a way to split a Flutter app into parts with separate jobs. The widgets draw the screen. A view model decides what the screen should show. Repositories and services fetch and store the data. This chapter gives you the vocabulary and the overall shape. Later chapters build each piece in detail.
Prerequisites
This chapter assumes you already have:
- Basic Dart: classes,
async/await, andFuture. - Flutter widgets:
StatelessWidget,StatefulWidget, andbuildmethods. - Experience with
setState, including how it gets hard to manage once a widget grows large.
The problem MVVM solves
A common first Flutter app keeps everything in one State class. The State object calls the network, parses the response, tracks isLoading and error flags, and builds the widgets. This works for small screens. As the screen grows, three problems appear:
- Testing needs widgets. To check that an error message appears after a failed request, you have to pump a widget tree and fake the network.
- Logic is hard to reuse. Two screens that need the same data each carry their own copy of the fetching code.
- Changes spread. Renaming a field in an API response forces edits in widget code.
MVVM fixes these by moving everything that is not drawing out of the widget. The widget becomes a function of some state, and the state lives in an object you can test as plain Dart.
The roles
Flutter's official architecture guidance describes MVVM with these parts. The names below are used throughout this tutorial.
| Part | Layer | Job |
|---|---|---|
| View | UI layer | Widgets that render state and forward user input. No business logic. |
| View model | UI layer | Holds the UI state for one screen, exposes it read-only, and handles user actions. |
| Repository | Data layer | Single source of truth for one kind of data. Hides where the data comes from. |
| Service | Data layer | Wraps one external source, such as an HTTP API or local storage. |
| Model | Data layer | Immutable classes that describe the data, such as a `Todo`. |
The word "model" is the confusing one. In classic MVVM the model is the whole data side. In Flutter's guidance, the data side is split into repositories, services, and data model classes. When this tutorial says "model", it means a data class such as Todo.
View
A view is a widget, or a small tree of widgets. It does two things only. It reads state from a view model and builds UI from it. When the user taps, types, or scrolls, it calls a method on the view model. A view should not call a repository, parse JSON, or decide whether an error is retryable.
View model
A view model is a plain Dart class that holds the state for one screen and the methods that change it. In this tutorial it extends ChangeNotifier, a class from Flutter's foundation library that keeps a list of listeners and calls them when you invoke notifyListeners(). A view model typically exposes:
- Read-only getters for state, such as
todos,isLoading, anderror. - Methods for user actions, such as
load()andtoggle(todo).
It depends on repositories, not on widgets. It never imports a BuildContext.
Repository and service
A repository answers the question "give me the todos" without revealing whether they come from memory, a database, or a server. It may combine several services, cache results, and convert raw responses into data models. A service is the thin wrapper at the edge: it knows the URL, the SDK call, or the file path, and nothing else. This split lets you replace a service without touching the view model.
How the pieces connect
Dependencies point in one direction. The view knows the view model. The view model knows the repository. The repository knows the services. No part knows about the part above it.
Read the diagram as a loop. The user acts, the view model asks for or changes data, the new state is stored in the view model, and the view rebuilds from that state. The view never edits state directly. Chapter 11 returns to this idea under the name unidirectional data flow.
A minimal working example
The smallest MVVM setup has a view model and a view. There is no repository yet. A counter shows the mechanism without any data layer.
import 'package:flutter/material.dart';
class CounterViewModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
void main() => runApp(const MaterialApp(home: CounterScreen()));
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key});
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
final CounterViewModel _viewModel = CounterViewModel();
@override
void dispose() {
_viewModel.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: ListenableBuilder(
listenable: _viewModel,
builder: (context, _) => Text('Count: ${_viewModel.count}'),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _viewModel.increment,
child: const Icon(Icons.add),
),
);
}
}Three details carry over to every later chapter:
- The state
_countis private. The view can readcountbut cannot assign it. increment()changes the state and then callsnotifyListeners(). If you forget the call, the data changes but the screen does not.ListenableBuildersubscribes to the view model and runs itsbuilderagain on each notification. Only that subtree rebuilds, not the whole screen.
The State class here only creates and disposes the view model. Counting is not its job. Later chapters move creation out of the widget through dependency injection.
MVVM compared with putting logic in `State`
Using setState is not wrong. It is the right tool for state that belongs to one widget, such as whether a text field is focused or which tab is selected. MVVM targets state that is tied to your app's data and behavior.
| Question | `State` with `setState` | View model |
|---|---|---|
| Where does fetching code live? | In the widget class | In the view model, through a repository |
| Can you unit test it without widgets? | No, you need `testWidgets` | Yes, plain `test` |
| Can two widgets share the state? | Only by passing it down or lifting it up | Yes, by sharing one view model instance |
| Cost | None | Extra classes and wiring |
A useful rule is to ask whether the state would survive being described without mentioning a widget. "The list of todos and whether it is loading" can be described that way, so it belongs in a view model. "Whether this expansion tile is open" cannot, so it can stay in State.
What this tutorial builds
Over the next chapters you will build a todo list app with these parts:
- An immutable
Tododata model. - A
TodoRepositoryinterface and an in-memory implementation. - A
TodoListViewModelthat exposestodos,isLoading, anderror. - A
TodoScreenthat rebuilds withListenableBuilder, then a version wired with theproviderpackage. - Unit tests that use a fake repository.
Each chapter adds one idea, so you can stop at any point with something that runs.
Common misunderstandings to avoid early
- "The view model is the model." The view model holds presentation state for a screen. Data classes and repositories are separate.
- "One view model per app." Aim for one view model per screen or per self-contained feature. A single large one recreates the original problem.
- "The view model can hold a
BuildContext." It should not. Navigation and dialogs are triggered by the view reacting to state, which keeps the view model testable. - "More layers are always better." For a screen with a single static list, a view model and repository may be more code than the problem needs. The final chapter covers when to skip them.
Exercise
A screen shows a list of products fetched from a server. It also has a search box with a focus highlight. Which of these belong in a view model, and which can stay in the widget's State: the product list, the loading flag, the focus highlight, the call to the server?
Show answer
The product list and the loading flag belong in the view model, because they describe the app's data and can be described without mentioning a widget. The server call belongs behind a repository (and service) that the view model uses, not in the widget. The focus highlight is purely visual state for one widget, so it can stay in State.
Exercise
In the counter example, what visible symptom appears if you remove the notifyListeners() call from increment(), and why?
Show answer
The count variable still increases, but the text on screen never changes. ListenableBuilder only runs its builder when the view model notifies its listeners, so without the call the view is never told to rebuild.