Reputation: 549
I am trying to make an observable list (i.e. when an element of the list is changed, removed, or added, I would like the UI to updated). I know that mobx has something called an "observableList", and so this seems like it should be possible. However, I am having issues implementing it. I currently have the following code in my mobx store file:
var metrics = Observable([.5,.5,.5]);
Then later, I try to change one of the elements like so:
metrics[index] = data;
I get the error:
The method '[]=' isn't defined for the class 'Observable>'.
Is there a way to create an observable list (or better yet, an observable dictionary) in flutter, or is that not implemented yet?
Thanks!
Upvotes: 8
Views: 21518
Reputation: 2287
You can use my code. You need to add ".of" to initialize the list
ObservableList<int> values = ObservableList<int>.of([1,2,3]);
Later you can use it like this.
values[index] = data;
Upvotes: 12
Reputation: 4741
With MobX you need to create methods annotated with @action
to be notified about changes over an Observable
.
@observable
var metrics = ObservableList<int>([.5,.5,.5]);
// This is action method. You need to use this method to react
// your UI properly when something changes in your observable list.
@action
void addItem(float data) => metrics.add(data);
// the same for this method but with a different operation.
@action
void removeItem(float data) => metrics.remove(data);
#In your UI layer
Observer(
builder: (context) =>
ListView.builder(
itemCount: yourStore.metrics.length,
builder: (_, index) => Text('${yourStore.metrics[index]}'),
),
);
In this case after some change in yourStore.metrics
observable list the Observer
builder callback will be fired and the list view will be updated.
Upvotes: 15