Why we use sometimes notifyListeners and also why we do not use notifyListeners? How can we use a function in changenotifier ?
For instance, in this code, sometimes we used to notifyListeners, but sometimes we did not use notifyListeners (in login() function). Why ? When we use notifyListeners?
String get userEmail => _userEmail;
set userEmail(String value) {
_userEmail = value;
notifyListeners();
}
String get userPassword => _userPassword;
set userPassword(String value) {
_userPassword = value;
notifyListeners();
}
String get userName => _userName;
set userName(String value) {
_userName = value;
notifyListeners();
}
DateTime get dateOfBirth => _dateOfBirth;
set dateOfBirth(DateTime value) {
_dateOfBirth = value;
notifyListeners();
}
Future<bool> login() async {
try {
isLoading = true;
print(userEmail);
print(userPassword);
if (isLogin) {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: userEmail,
password: userPassword,
);
} else {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: userEmail,
password: userPassword,
);
}
isLoading = false;
return true;
} catch (err) {
print(err);
isLoading = false;
return false;
}
}
}
Besides can someone answer me about why we use set method in this code
bool get isLogin => _isLogin;
set isLogin(bool value) {
_isLogin = value;
notifyListeners();
}
The method
notifyListeners()
is used whenever you want to trigger a rebuild or whenever there is an active listener which is monitoring for the change to perform certain actionsAssume a scenario, You have a data model, and as soon as you fetch the data from APIs you want to parse it and fill in the model class, Also you want that UI will automatically rebuild after getting the data !
For this purpose you can use
notifyListeners()
in data class and in your UI code, You can wrap the parts which needs to be rebuild with aChangeNotifierProvider
or aConsumer
Widget that will monitor for changes and as soon as they encounter any change , They will rebuild the underlying Widget(s).In the code you shared above, You've used
private
fields that cannot be accessed outside of this file and you are usinggetters
andsetters
to basically retrieve them and modify themAnswering your last question now, We use
set
method orsetter
to basically update or modify a value (generally a private value)Just to provide you some additional info, You should NOT wrap fields in getters and setters just to be "safe". This method is Old and not needed in Dart language
You can read more about this here
You can also read about getters and setters in dart here.
Since you are new to StackOverflow, I welcome you. Happy Fluttering !