Learn/Architecture Patterns/MVVM & Repository Pattern

MVVM & Repository Pattern

Implement Model-View-ViewModel with Repository pattern

7 min~5 min read+40 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. ViewModel Contract Design
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

MVVM & Repository Pattern

MVVM (Model-View-ViewModel) is a UI architecture pattern that separates your app into three roles. The Model represents your data classes and business objects. The View is your Flutter widgets that render the UI. The ViewModel sits between them, holding UI state like loading flags, error messages, and transformed data. It exposes methods that the View calls and notifies the View when state changes. The Repository Pattern complements MVVM by abstracting where data comes from. Your ViewModel asks the Repository for data without knowing whether it came from an API, local database, or cache. This separation makes your code highly testable because you can replace any layer with a mock during testing.

dart
1// ── Model ──
2class Product {
3 final String id;
4 final String name;
5 final double price;
6 Product({required this.id, required this.name, required this.price});
7
8 factory Product.fromJson(Map<String, dynamic> json) => Product(
9 id: json['id'], name: json['name'], price: json['price'].toDouble(),
10 );
11}
12
13// ── Repository ──
14class ProductRepository {
15 final ApiService _api;
16 final DatabaseService _db;
17 ProductRepository(this._api, this._db);
18
19 Future<List<Product>> getProducts() async {
20 try {
21 final products = await _api.fetchProducts();
22 await _db.cacheProducts(products); // cache for offline
23 return products;
24 } catch (e) {
25 return _db.getCachedProducts(); // fallback to cache
26 }
27 }
28}
29
30// ── ViewModel (with ChangeNotifier) ──
31class ProductViewModel extends ChangeNotifier {
32 final ProductRepository _repository;
33 ProductViewModel(this._repository);
34
35 List<Product> _products = [];
36 bool _isLoading = false;
37 String? _error;
38
39 List<Product> get products => _products;
40 bool get isLoading => _isLoading;
41 String? get error => _error;
42
43 Future<void> loadProducts() async {
44 _isLoading = true;
45 _error = null;
46 notifyListeners();
47
48 try {
49 _products = await _repository.getProducts();
50 } catch (e) {
51 _error = e.toString();
52 }
53
54 _isLoading = false;
55 notifyListeners();
56 }
57}
58
59// ── View (Widget) ──
60Consumer<ProductViewModel>(
61 builder: (context, vm, child) {
62 if (vm.isLoading) return const CircularProgressIndicator();
63 if (vm.error != null) return Text('Error: ${vm.error}');
64 return ListView.builder(
65 itemCount: vm.products.length,
66 itemBuilder: (context, i) => ListTile(
67 title: Text(vm.products[i].name),
68 subtitle: Text('\$${vm.products[i].price}'),
69 ),
70 );
71 },
72)

Repository Benefits

💡 Repository Benefits

The repository pattern lets you swap data sources without changing UI code. Your ViewModel never knows if data came from API, cache, or mock: making testing trivial.

ViewModel Contract Design

Treat each ViewModel as a contract for one screen or flow:

  • Public state should be explicit (idle, loading, success, failure).
  • ViewModel methods should describe intent (loadProducts, refresh, retry).
  • Data transformation for display belongs in ViewModel, not in widgets.
  • Repository exceptions should be mapped to stable UI error states.

When ViewModel contracts are clear, UI code remains simple and easier to test.

MVVM Reliability Checklist

  • Views only read exposed state and call ViewModel intent methods.
  • ViewModel has unit tests for loading, success, empty, and failure paths.
  • Repository fallback logic is deterministic and covered by tests.
  • No direct API or database calls occur inside widget classes.
  • Error messages shown to users are clear and actionable.

This Lesson In Simple Words

Implement Model View ViewModel with Repository pattern. State is data that changes over time and controls what users see on the screen.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Keep state as close as possible to where it is used, then lift it only when sharing is required.

Deep Understanding Guide

Why this lesson matters

State management is the difference between predictable apps and hard-to-debug UI behavior.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Trace one user action from button tap to state update to rebuilt UI.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Calling setState high in the tree when only a small part needs refresh.
  • Keeping duplicated state in multiple widgets without a single source of truth.
  • Mutating collections directly and expecting UI updates automatically.
  • Choosing a heavy state library before understanding simple local state.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one feature with local setState, then refactor it to Provider or Riverpod.
  • Create loading, success, and error states for one async user flow.
  • Write a small state diagram for a login form and implement it.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does the ViewModel contain in MVVM?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • repository: A layer that hides data source details from the UI layer.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

State boundaries define module boundaries, so clear ownership prevents future regressions.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "MVVM & Repository Pattern" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Calling setState high in the tree when only a small part needs refresh.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does the ViewModel contain in MVVM?

The ViewModel holds UI state (isLoading, error, data) and methods that the View can call.

What does the Repository Pattern abstract?

The repository abstracts where data comes from (API, local DB, cache), providing a clean interface to ViewModels.

In MVVM, which component directly interacts with the user?

The View (widgets) is the UI layer that users interact with. It delegates logic to the ViewModel.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue