2

I have a StateNotifier whose state I want to use in a widget.

As far as I know, if you watch a StateNotifierProvider with ref.watch in a build, the widget gets rebuilt every time the state changes.

Now, In the StateNotifier I have a DatabaseService instance to call api requests and set the state accordingly and in a ConsumerWidget I watch the state.

The thing is, I want to call a fetch method defined in StateNotifier the first time the widget builds, so I can display the data retrieved from the database.

Something like this

class MyStateNotifier extends StateNotifier<CustomState> {
  final DatabaseService databaseService;      

  MyStateNotifier(this.databaseService) : super(CustomStateInit());

  Future<void> fetchData() async {
    state = CustomStateLoading();

    final result = await databaseService.apiRequest();

    state = CustomStateSuccess(result);
  }
}

final stateNotifierProvider = StateNotifierProvider((ref) => MyStateNotifier());

and in the widget

class MyWidget extends ConsumerWidget {
  // I have to call the MyStateNotifier fetchData() method to get the data

  Widget build(BuildContext context, WidgetRef ref) {
    final data = ref.watch(stateNotifierProvider);

    return Column(
      children: data.map((e) => Text(e)).toList()
    );
  }
}
Ghost
  • 401
  • 3
  • 15

1 Answers1

0

To call fetchData() once you watch your stateNotifierProvider you need to call it in the StateNotifier's constructor like this:

MyStateNotifier(this.databaseService) : super(CustomStateInit()){fetchData();}
Mohammad Alotol
  • 1,409
  • 15
  • 23