Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable Lists in flutter with mobx

Tags:

flutter

dart

mobx

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!

like image 715
gollyzoom Avatar asked Dec 04 '22 17:12

gollyzoom


1 Answers

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.

like image 195
Marcos Boaventura Avatar answered Jan 04 '23 12:01

Marcos Boaventura