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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With