Sub topic 2
Separating the UI Layer from the Data Layer
This chapter assumes basic Dart syntax, async and await, Flutter widget composition, and familiarity with setState. The goal is to separate code that displays state from code that obtains and changes data.
Why separate the layers?
In a small widget, it is tempting to fetch data and handle errors directly inside build or an event callback. As the app grows, the widget then knows about HTTP requests, storage, parsing, loading flags, and error handling. This makes the widget difficult to read and test.
MVVM divides these responsibilities:
- The view is the widget tree. It displays state and forwards user actions.
- The view model stores UI state and coordinates actions for one view.
- The repository defines how the application reads and changes a type of data.
- A service talks to a specific external source, such as an HTTP API or a database.
- A model represents application data.
The view should not need to know whether todos come from a server, a file, or memory.
Define boundaries with interfaces
An interface describes an operation without specifying its implementation. In Dart, an abstract class can define this boundary. The view model depends on the repository interface, not on a concrete HTTP client.
import 'package:flutter/foundation.dart';
class Todo {
const Todo({required this.id, required this.title});
final int id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
}
class ApiTodoService {
Future<List<Todo>> getTodos() async {
// A real service would call an HTTP endpoint and parse its response.
return const [
Todo(id: 1, title: 'Learn MVVM'),
Todo(id: 2, title: 'Test the view model'),
];
}
}
class TodoRepositoryImpl implements TodoRepository {
TodoRepositoryImpl(this.service);
final ApiTodoService service;
@override
Future<List<Todo>> fetchTodos() => service.getTodos();
}
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<Todo> _todos = const [];
bool _isLoading = false;
Object? _error;
List<Todo> get todos => List.unmodifiable(_todos);
bool get isLoading => _isLoading;
Object? get error => _error;
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (error) {
_error = error;
} finally {
_isLoading = false;
notifyListeners();
}
}
}The repository is a useful boundary because it can combine several services, map remote data into Todo objects, or choose a cache. None of those decisions belong in the view.
Keep state flowing in one direction
A typical interaction follows this sequence:
- The view model asks the repository for data.
- The repository uses a service and returns models.
- The view model changes its private state.
notifyListeners()tells the view to rebuild.- The view reads getters and displays the new state.
The view sends commands inward, while state flows outward. This makes the source of a change easier to find.
Exercise
Exercise
Why should TodoListViewModel depend on TodoRepository instead of TodoRepositoryImpl?
Show answer
The interface hides the data source and allows a fake repository to replace the real implementation during tests.