7

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!

Augustin R
  • 7,089
  • 3
  • 26
  • 54
gollyzoom
  • 519
  • 1
  • 6
  • 21

2 Answers2

14

With MobX you need to create methods annotated with @action to be notified about changes over an Observable.

In your Store you must have something like

@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.

John Joe
  • 12,412
  • 16
  • 70
  • 135
Marcos Boaventura
  • 4,641
  • 1
  • 20
  • 27
  • 1
    Is this true? In the docs, they demonstrate Observables triggering Reactions without having to wrap them in Actions. I thought Actions are just for making multiple changes atomic, ie, trigger a single Reaction...? https://pub.dev/packages/mobx – Hari Honor Jul 15 '21 at 08:45
  • @HariHonor You are correct. Additionally, you do not need to wrap an ObservableList with `@observable`, and you do not need to wrap list-modifying actions with `@action` https://pub.dev/documentation/mobx/latest/mobx/ObservableList-class.html – Taylor Gronka Sep 10 '22 at 21:24
9

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;