'in Flutter, what is the difference between .addListener(nofityListeners) and .notifyListeners?
I am not even sure xxManager.notifyListeners() is valid because what I saw so far is just plain notifyListeners() being used in class that extend ChangeNotifier for example :
Timer(
const Duration(milliseconds: 2000),
() {
_initialized = true;
notifyListeners();
},
);
here i tried to understand the meaning of
class AppRouter extends RouterDelegate<AppLink>
with
ChangeNotifier,
PopNavigatorRouterDelegateMixin {
@override
final GlobalKey<NavigatorState> navigatorKey;
final AppStateManager appStateManager;
final XXManager xxManager;
final YYManager yyManager;
AppRouter({
required this.appStateManager,
required this.xxManager,
required this.yyManager,
})
: navigatorKey = GlobalKey<NavigatorState>() {
appStateManager.addListener(notifyListeners); <-------This part
.
.
.
}
that part of the code for what I understand is to add listener to see the change in appStateManager which if changes will trigger notifyListeners method. what i dont understand is when i change it into:
appStateManager.notifyListeners();
it didnt show any error but when I ran it apparently it does not listen nor notify (the appStateManager has a Timer function which change the state in this case isInitialized to true after 2s so if the listener catch it, it will "route to next widget" (hope i said it correctly)). with 1st case it will change screen after 2s but on 2nd case it does nothin. what is wrong?
Solution 1:[1]
It's pretty straight forward.appStateManager.addListener() adds listeners.appStateManager.notifyListeners() notifies those listeners.
But with this line:appStateManager.addListener(notifyListeners);
You are adding listeners with the name notifyListeners. notifyListeners is a variable here. It's not the same as the method
Solution 2:[2]
addListener is register a closure to be called when the object changes.
notifyListeners is Calling all the registered listeners.
Note that:
- with addListener, if you want to add an instance, then it must be removed the same number of times it is added before it will stop being called.
- these methods must not be called after dispose has been called.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ivo Beckers |
| Solution 2 | Mohamed Reda |
