Sub topic 2
Separating the UI Layer from the Data Layer
This chapter assumes you know Dart classes, async/await, and Future. It also assumes you can build StatelessWidget and StatefulWidget classes and have felt setState get unwieldy in a large widget. The chapter shows where each piece of an MVVM app lives. Later chapters build each piece in detail.
Why split an app into layers
A first Flutter screen often does everything in one State class. It calls an HTTP client, parses JSON, stores the result in a field, and rebuilds with setState. This works for one screen. It becomes a problem when you want to:
- Test the logic without pumping widgets.
- Reuse the same data on two screens.
- Swap a real server for a fake during development.
- Change the screen's layout without touching how data is fetched.
Layering fixes this by giving each class one job and limiting which classes may know about which. The Flutter team's architecture guidance describes two main layers, the UI layer and the data layer. A third, optional domain layer sits between them and is not covered here.
The two layers
The UI layer shows data and handles user input. It contains views and view models.
The data layer gets, stores, and changes data. It contains repositories and services.
| Layer | Class type | Job |
|---|---|---|
| UI | View | Widgets that draw the screen and forward user events |
| UI | View model | Holds the state the view needs and exposes actions |
| Data | Repository | Single source of truth for one kind of data; hides where it comes from |
| Data | Service | Wraps one external source such as an HTTP API or local storage |
Data models, such as the Todo class, are plain objects that both layers share.
The dependency rule
The important property of this diagram is that dependencies point downward. Each class knows only about the layer directly beneath it:
- A view knows its view model. It does not know repositories or services.
- A view model knows repositories. It does not know widgets or
BuildContext. - A repository knows services. It does not know view models.
- A service knows nothing about the app's own classes.
The view model also reaches back to the view, but only through notification. It calls notifyListeners, and it never holds a reference to a widget. Chapter 3 covers that mechanism.
This rule is what makes the benefits above possible. Because the view model never imports package:flutter/material.dart, you can test it as plain Dart. Because the view only sees the view model, you can rewrite the screen without touching data code.
What each class is responsible for
The view
A view is a widget. It reads state from the view model and draws it. When the user taps something, the view calls a method on the view model and does nothing else. A view may hold purely visual state, such as a text field controller, an animation, or which tab is selected, when no other part of the app cares about it. It should not decide how to load data or what a failed request means.
The view model
A view model turns data-layer information into the shape the screen needs, and it exposes actions the screen can trigger. In the TodoListViewModel from this tutorial, that means a list of todos, an isLoading flag, and an error value, plus load() and toggle() methods. It extends ChangeNotifier so views can listen for changes.
The repository
A repository is the single place the rest of the app asks for one kind of data. The view model calls fetchTodos() and does not care whether the answer came from a server, a cache, or memory. A repository can combine several services, cache results, and translate service-specific data into the app's own models.
The service
A service wraps one external source: an HTTP client, a database, a platform channel, or a file. Its API stays close to that source. A service might return raw JSON maps, and the repository converts them into Todo objects. Services keep messy details such as URLs, headers, and storage keys in one place.
A concrete example of the split
The tutorial's todo app has a repository interface and an in-memory implementation:
class Todo {
const Todo({required this.id, required this.title, this.done = false});
final int id;
final String title;
final bool done;
Todo copyWith({String? title, bool? done}) =>
Todo(id: id, title: title ?? this.title, done: done ?? this.done);
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> setDone(int id, bool done);
}
class InMemoryTodoRepository implements TodoRepository {
final List<Todo> _todos = [
const Todo(id: 1, title: 'Write the view model'),
const Todo(id: 2, title: 'Connect the view'),
];
@override
Future<List<Todo>> fetchTodos() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return List.unmodifiable(_todos);
}
@override
Future<void> setDone(int id, bool done) async {
final index = _todos.indexWhere((t) => t.id == id);
if (index == -1) throw ArgumentError('Unknown todo $id');
_todos[index] = _todos[index].copyWith(done: done);
}
}Here the InMemoryTodoRepository stands in for a real service. In a production app you would add a service class, for example one wrapping an HTTP client, and have the repository call it. The view model would not change at all, because it depends on the TodoRepository interface.
Notice what the interface exposes. It speaks in Todo objects and plain Future values. It says nothing about JSON, status codes, or SQL. That is the repository's main job: translating from the data source's vocabulary into the app's vocabulary.
Where logic goes
The most common layering decision is "where does this code belong?" Use this table as a guide.
| Code | Belongs in |
|---|---|
| Padding, colors, layout, animations | View |
| Choosing which widget to show for loading or error state | View, reading flags from the view model |
| Setting `isLoading` to true, catching exceptions, storing the error | View model |
| Sorting or filtering for display | View model |
| Deciding whether data is stale or cached | Repository |
| Building URLs, parsing JSON, reading files | Service (parsing into models may sit in the repository) |
A useful test is to ask whether the code would change if the UI were redesigned. If not, it should not be in a widget.
Edge cases and trade-offs
Repositories can return data directly or expose streams. The example uses Future for one-shot reads. If several screens must stay in sync with the same data, the repository can expose a Stream or be a ChangeNotifier itself. This tutorial keeps repositories plain and has the view model re-fetch after a change.
A view model per screen is a good default. Sharing one view model across unrelated screens couples them. Sharing a repository across many view models is normal and is the reason the repository exists.
Thin pass-through layers are a cost. If a repository method only forwards a call to a service and the service only forwards to an HTTP client, you have added classes without adding value. The layers earn their place when you add caching, error translation, or a second data source. Chapter 16 returns to when MVVM is more structure than a small app needs.
Errors cross layers. A service may throw an HttpException. If the view model catches it and stores it as-is, the view ends up depending on a networking type. A cleaner approach is for the repository to translate service errors into app-level errors, or for the view model to store a user-friendly message. The todo example stores the raw object for simplicity, and later chapters discuss improving it.
Models are shared, not owned. Immutable data models such as Todo are the one thing that crosses every boundary. Making them immutable, with copyWith for changes, prevents a view from mutating data the repository still holds.
Checking your understanding
Exercise
A teammate's TodoScreen widget calls http.get(...) directly inside initState, parses the JSON, and stores a List<Todo> in a State field. Name the classes you would create to move this code into the layers described in this chapter, and say which layer each one belongs to. Then say which one the widget should depend on afterward.
Show answer
Create a service (data layer) that wraps the http call and returns raw JSON. Create a TodoRepository (data layer) that uses the service and parses the JSON into Todo objects. Create a TodoListViewModel (UI layer) that extends ChangeNotifier, calls the repository, and holds the todos, loading flag, and error. The widget (UI layer, the view) should depend only on the view model, and it never imports the service or repository.
Exercise
A view model file contains import 'package:flutter/material.dart'; and calls Navigator.of(context).push(...) after a save succeeds. Which part of the dependency rule does this break, and what is one consequence for testing?
Show answer
It breaks the rule that a view model must not know about widgets or BuildContext. The view model now depends on the widget framework and on a live context, so testing it requires a widget test environment and a real or mocked BuildContext instead of plain Dart. A better design has the view model expose state, such as a saved flag, and lets the view decide whether to navigate.