Sub topic 1
What MVVM means in a Flutter app
Prerequisites
This chapter assumes you know Dart classes, async/await, and Future. You should also be comfortable with StatelessWidget and StatefulWidget, and you should have seen how setState rebuilds a widget.
The three roles
Model-View-ViewModel (MVVM) splits a screen into three parts. The view is the widget tree that draws the screen. The view model holds the state the view needs and decides what happens when the user acts. The model is the data and the code that fetches or stores it.
Separating the UI layer from the data layer
The UI layer holds the view and view model. The data layer holds repositories and services. Keep widgets free of business rules and network calls. A widget that calls an API directly becomes hard to test and hard to change.
How ChangeNotifier notifies listeners
ChangeNotifier is a class from package:flutter/foundation.dart. It keeps a list of listeners and calls them when you call notifyListeners().
import 'package:flutter/foundation.dart';
class CounterModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}Each call to notifyListeners() tells every listener to rebuild. Call it only after the state has changed.
Designing the state a view needs
Expose only what the view reads. Give the view simple values such as isLoading, error, and a list of items. Keep the fields private and expose them through getters, so the view cannot change them directly.
Immutable data models
An immutable object cannot change after it is created. Use final fields and a copyWith method to make a changed copy.
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);
}Immutable models make state changes easier to follow, because each update creates a new value instead of mutating a shared one.
Exercise
The CounterModel above calls notifyListeners() inside increment(). Why should it be called after _count changes rather than before?
Show answer
Listeners rebuild as soon as they are notified and read the current state. If you notify first, they read the old value and the view shows stale data.