What does the ViewModel contain in MVVM?
The ViewModel holds UI state (isLoading, error, data) and methods that the View can call.
Implement Model-View-ViewModel with Repository pattern
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
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 (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.
1// ── Model ──2class Product {3final String id;4final String name;5final double price;6Product({required this.id, required this.name, required this.price});78factory Product.fromJson(Map<String, dynamic> json) => Product(9id: json['id'], name: json['name'], price: json['price'].toDouble(),10);11}1213// ── Repository ──14class ProductRepository {15final ApiService _api;16final DatabaseService _db;17ProductRepository(this._api, this._db);1819Future<List<Product>> getProducts() async {20try {21final products = await _api.fetchProducts();22await _db.cacheProducts(products); // cache for offline23return products;24} catch (e) {25return _db.getCachedProducts(); // fallback to cache26}27}28}2930// ── ViewModel (with ChangeNotifier) ──31class ProductViewModel extends ChangeNotifier {32final ProductRepository _repository;33ProductViewModel(this._repository);3435List<Product> _products = [];36bool _isLoading = false;37String? _error;3839List<Product> get products => _products;40bool get isLoading => _isLoading;41String? get error => _error;4243Future<void> loadProducts() async {44_isLoading = true;45_error = null;46notifyListeners();4748try {49_products = await _repository.getProducts();50} catch (e) {51_error = e.toString();52}5354_isLoading = false;55notifyListeners();56}57}5859// ── View (Widget) ──60Consumer<ProductViewModel>(61builder: (context, vm, child) {62if (vm.isLoading) return const CircularProgressIndicator();63if (vm.error != null) return Text('Error: ${vm.error}');64return ListView.builder(65itemCount: vm.products.length,66itemBuilder: (context, i) => ListTile(67title: Text(vm.products[i].name),68subtitle: Text('\$${vm.products[i].price}'),69),70);71},72)
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.
Treat each ViewModel as a contract for one screen or flow:
When ViewModel contracts are clear, UI code remains simple and easier to test.
Implement Model View ViewModel with Repository pattern. State is data that changes over time and controls what users see on the screen.
Think in architecture, reliability, and team-level maintainability.
Keep state as close as possible to where it is used, then lift it only when sharing is required.
State management is the difference between predictable apps and hard-to-debug UI behavior.
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.
The ViewModel holds UI state (isLoading, error, data) and methods that the View can call.
The repository abstracts where data comes from (API, local DB, cache), providing a clean interface to ViewModels.
The View (widgets) is the UI layer that users interact with. It delegates logic to the ViewModel.
Something seems incorrect, unclear, or missing? Let us know.
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