Im testing mobx and created a class to get data from an API and store in a observable list and its working ok.
@observable
List<UserModel> users = ObservableList<UserModel>();
@action
fetchUsers() async {
var usersApi = await userApiService.getUsers();
users = usersApi;
}
Now i want to add a new item to this list:
`
@action
addUser() {
final usr = UserModel(
email: '[email protected]',
firstName: 'User',
lastName: 'New User');
users.add(usr);
}
`
When i call addUser action, the user is added to the list, but in my view, the observer dont rebuilds to show the new user. How can i fix it?
thanks
Can you share your Observer related code ?
Hi @pavanpodila , my observer is a simple Listview:
Observer(
builder: (BuildContext context) {
return (usersController.usersList.length != 0)
? Container(
height: 300,
child: ListView.builder(
itemCount: usersController.usersList.length,
itemBuilder: (BuildContext context, int index) {
final user = usersController.usersList[index];
return ListTile(
title: Text('${user.firstName} - ${user.email}'),
);
},
),
)
: Center(
child: CircularProgressIndicator(),
);
},
),
When i use the action fetchUsers, the observer is ok, but when i try to add a new item to the observableList, the observer dont show the new item.
Observer only observes the observables used in its immediate builder function. Hence it can't see into the nested functions. In your case, you should also wrap the ListView.builder inside an Observer.
@pavanpodila thanks for the reply.
I did as you mentioned. Wrap my Listview in a Observer
Here's the complete code:
Observer(
builder: (BuildContext context) {
return (usersController.usersList.length != 0)
? Container(
height: 300,
child: Observer(
builder: (BuildContext context) {
return ListView.builder(
itemCount: usersController.usersList.length,
itemBuilder: (BuildContext context, int index) {
final user = usersController.usersList[index];
return ListTile(
title:
Text('${user.firstName} - ${user.email}'),
);
},
);
},
))
: Center(
child: CircularProgressIndicator(),
);
},
),
But the list only rebuilds if i do a Hot Reload. I have made a mistake? Thanks
Can you share the complete code in a small repo ? Not able to suggest based on the code you shared.
try
@observable
ObservableList<UserModel> users = new ObservableList<UserModel>();
and
flutter packages pub run build_runner watch --delete-conflicting-outputs
closing for being stale
Observeronly observes the observables used in its immediatebuilderfunction. Hence it can't see into the nested functions. In your case, you should also wrap theListView.builderinside anObserver.
Could you please point me to documentation page which says that?
Most helpful comment
Observeronly observes the observables used in its immediatebuilderfunction. Hence it can't see into the nested functions. In your case, you should also wrap theListView.builderinside anObserver.