mobxjs / mobx.dart

MobX for the Dart language. Hassle-free, reactive state-management for your Dart and Flutter apps.
https://mobx.netlify.app
MIT License
2.4k stars 310 forks source link

When adding an item to an ObservableList and it is observed, the index is length of the list #193

Closed MaikuB closed 5 years ago

MaikuB commented 5 years ago

I've defined a store as follows

import 'package:mobx/mobx.dart';
import '../models/item.dart';

part 'data_store.g.dart';

class DataStore = _DataStore with _$DataStore;

abstract class _DataStore with Store {
  @observable
  ObservableList<Item> items = ObservableList<Item>();

  @action
  void addItem() {
    items.add(Item(DateTime.now().toUtc()));
  }
}

In one of my widgets, I observe if the list has been modified

@override
  void initState() {
    super.initState();
    widget.store.items.observe((listChange) {
      if (listChange.added?.isNotEmpty ?? false) {
        <handle when item has been added>
      }
    });
  }

When an item has been added via the addItem method within the store, the callback is invoked in the widget to notify me that an item has been added. Upon inspect the value of listChange.index, it appears that rather than being the index of where the item has been added, it's actually the length of the list. For example, if this is the first item that's been added, I'm expecting listChange.index to have a value of 0, instead the actual value is 1

Provided it's an actual bug (which I suspect is the case), this appears to be where the fix needs to be applied

Edit: code snippets are taken from this repo https://github.com/MaikuB/flutter_mobx_animatedlist_demo if you need to be able to reproduce the issue. I can look at submitting a PR as well though should be an easy fix

pavanpodila commented 5 years ago

Hey @MaikuB, that is indeed a bug 🥇. I'll be more than happy to take in a PR.

I think that way you also get a taste of how MobX works internally and get a chance to explore other collection types: ObservableMap, ObservableSet and of course ObservableList to see if similar issues exist over there. Want to take a crack at it ?

MaikuB commented 5 years ago

Sure. Won't be till much later that I can take a look though. Getting late in Australia so struggling to stay up to watch the cricket and code at the same time ;)

pavanpodila commented 5 years ago

Ha ha, same here...as in "Watching Cricket". Take rest and get back when you can. Great ideas might come in the sleep 😀