Reputation: 1121
I have a General Provider
which is called on the start of the app.
it fetches
some data via API. Normally I would keep it to that Provider for flutter but as the app is growing I think its better to separate the logic for all.
This first API also brings in the user
data. Now I also have a UserProvider
in the app. I created the below for it.
class UserProvider extends ChangeNotifier {
UserModel _user;
UserProvider(this._user);
set setUser(user){
_user = user;
notifyListeners();
}
UserModel get getUser => _user;
}
No error here but question is how to call this setter
in GeneralProvider
class?
The way I know is as below:
UserProvider(UserModel(your_data));
`Provider.of(context).setUser(UserModel(your_data));
First one works for me. and second one don't in the provider part
.
Real issue with using first way
:
In my main.dart
where all the providers are provided, I need to do it like this.
ChangeNotifierProvider.value(
value: UserProvider(UserModel(your_data),
),
What I preferred is updating the UserProvider
when the general api
is called for base data
.
Upvotes: 3
Views: 3210
Reputation: 483
Updating this answer to newest version
context.watch<T>() // makes the widget listen to changes on T
context.read<T>() // returns T without listening to it
So here:
context.read<UserProvider>().setUser(NEW_USER);
Source: https://pub.dev/packages/provider#reading-a-value
Upvotes: 0
Reputation: 876
My solution was this setter in UserProvider class:
void setUser(User s) {
_user = s;
notifyListeners();
}
wrap your widget with:
return Consumer<UserProvider>(builder: (_,provider,__){
return WhateverYouWantToBuild(
...
),
});
and then calling it with:
provider.setUser(newValue!);
Upvotes: 1
Reputation: 2055
Here's the way:
Provider.of<UserProvider>(context, listen: false).setUser = your_parameter_here;
Probably you already found the solution, if not this is the answer.
Upvotes: 0