Home > front end >  Flutter Riverpod: StateNotifier not rerendering widget
Flutter Riverpod: StateNotifier not rerendering widget

Time:05-05

I have a simple StateNotifier class like so:

class MyClass extends StateNotifier<Map<String, dynamic>> {
  Map<String, dynamic> data;

  MyClass({this.data}) : super(null) {
    data = data ?? {};
  }

  setData(Map<String, dynamic> newData) {
    data = {...data, ...newData};
  }
}

I have my provider defined in a providers.dart file:

final myClassProvider = StateNotifierProvider((ref) => _myClass);

...which I'm importing and trying to "read" inside build of my widget and have the widget update when the state of MyClass changes:

MyClass _myClass = ref.watch(myClassProvider.notifier);

I have a couple of buttons which calls the setData method and I can see that it get's the new data, but my widget never rerenders. If I navigate back a screen and then forward again to the same view, I can see that it has been updated with the new data, but my widget never rerenders as it happens. Am I doing something fundamentally wrong here?

CodePudding user response:

StateNotifier has its own state.

class MyClass extends StateNotifier<Map<String, dynamic>> {

  MyClass(Map<String, dynamic> data) : super(data);

  setData(Map<String, dynamic> newData) {
    state = {...state, ...newData};
  }
}
  • Related