notifyListeners in flutter not working, i.e. the value is not at all updated
Regarding this line of codes in your question
UserProvider().setUser(
UserModel(
username: user['username'] ?? 'Guest',
email: user['id'] != null ? user['email'] : 'not available',
avatar: user['id'] != null ? user['avatar'] : 'not available',
),
);
where are you using it?, because it seems it creates new UserProvider() everytime when it is called...
Make sure it's called from the right place something like shown in official docs here https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => UserProvider(),
child: MyApp(),
),
);
}
princeoo7
Updated on December 20, 2022Comments
-
princeoo7 over 1 year
below is the code where for my
UserProvider
. The commented line in it is for the testing purpose and when it was used, I got theusername as "test"
in output on screen.class UserProvider with ChangeNotifier { // UserModel _user = UserModel(username: "test", isLoggedIn: false, isVerified: false); UserModel _user; setUser(UserModel user) { _user = user; notifyListeners(); print("user data changed !"); } UserModel get getUser => _user; }
Below is How I am updating data via a api call:
UserProvider().setUser( UserModel( username: user['username'] ?? 'Guest', email: user['id'] != null ? user['email'] : 'not available', avatar: user['id'] != null ? user['avatar'] : 'not available', ), );
there are not error in runtime and I have a line in the
setUser
method which is there to check if the method was called or notprint("user data changed !")
. and in terminal I do get this line out put, so the function is not skipped and definitely called.on screen I am calling the data as below:
UserModel user; @override void didChangeDependencies() { user = Provider.of<UserProvider>(context).getUser; super.didChangeDependencies(); }
and
Text("Hi, ${user.username}"),
Output is not the new data. its either
NULL
if the commented line is not used, and if used, theusername is test
.So where am I going wrong?
All help is appreciated.
Thank you for going through my question.
-
princeoo7 almost 4 yearsany update for me on the? as of now I am using the value from the general API. if the question is not answered, I will need to make multiple call for the small data on
splash screen
.
-