Home > other >  ValueNotifier does not notify listeners when modifying a list
ValueNotifier does not notify listeners when modifying a list

Time:12-28

I'm trying to rebuild list when an array changes:

ValueNotifier<List<String>> numbers = ValueNotifier(['123']);
numbers.addListener(() => print(numbers));
numbers.value.add('456');

However listener isn't called.

CodePudding user response:

you could do it with help of ChangeNotifier and ListMixin mixins:

class ListNotifier<T> extends ValueListenable<List<T>> with ChangeNotifier, ListMixin<T> {
  final List<T> _list = <T>[];

  @override
  set length(int newLength) {
    _list.length = newLength;
    notifyListeners();
  }

  @override
  int get length => _list.length;

  @override
  T operator [](int index) => _list[index];

  @override
  void operator []=(int index, T value) {
    _list[index] = value;
    notifyListeners();
  }

  @override
  void add(T element) {
    _list.add(element);
    notifyListeners();
  }

  @override
  List<T> get value => _list;
}

btw i did not test it with every list modification methods so better check it out

  • Related