Replace getter and setter blocks with a oneliner when using ChangeNotifier.

https://bsky.app/profile/sander-roest.bsky.social
Search for a command to run...

https://bsky.app/profile/sander-roest.bsky.social
No comments yet. Be the first to comment.
Running flutter upgrade is not enough...

A necessity or a rip-off?

Both are used by humans, but they are not the same.

Recap part 1. In the previous article about this subject, I explained the limitations that I have ran into, with the default onDidRemovePage implementation. In this article I will show how I’ve overcome or better said, circumvented these limitations....
During the development of my RubigoRouter package I ran into some limitations of the Navigator object that I explain here below. The Flutter Navigator has a mechanism to inform the app about a back navigation event. Historically the onPopPage callbac...
When dart became ‘non-nullable by default’, an interesting keyword was added to the dart language: ‘late’.
Although it might not be so obvious at first glance, this keyword makes it possible to simplify getter and setter blocks when using a ChangeNotifier to update values on the screen.
Normally a getter and setter block does look like this.
int _counter = 0;
int get counter => _counter;
set counter(int value) {
if (_counter != value) {
_counter = value;
notifyListeners();
}
}
This code is not complicated. It consists of:
There are also some drawbacks:
Now with the ‘late’ keyword, we can replace the code above with this one-liner:
late final counter = Property(0, notifyListeners);
Without the ‘late’ keyword this would not have been possible, because it is not allowed to access member functions (in this case notifyListeners) in an initializer. With the late keyword, initialization is deferred until the property is first referenced.
The implementation of the Property class is simple and solves all drawbacks of a regular getter and setter block.
class Property<T> {
Property(T initialValue, this.notifyListeners) {
_value = initialValue;
}
late T _value;
final void Function() notifyListeners;
T get value => _value;
set value(T value) {
if (_value != value) {
_value = value;
notifyListeners();
}
}
}
This makes it possible to reduce the business logic of the default Flutter counter app to these few lines:
class MainController extends ChangeNotifier {
late final counter = Property<int>(0, notifyListeners);
void incrementCounter() => counter.value++;
}
Source code to test this out can be found here:
https://github.com/jsroest/property_for_changenotifier