Search code examples
flutterriverpodriverpod-generatorriverpod-annotation

"Bad state: Tried to read the state of an uninitialized provider" with riverpod while listening to futureprovider


I have this generated notifier that should rebuild when the data changes without loosing its reference to a previously selected object on rebuild.

@Riverpod(keepAlive:true)
Future<List<MyModel>> modelList (ModelListRef ref) {
    return ref.watch(modelRepositoryProvider).getModels();
}

@Riverpod(keepAlive:true)
class MyController extends _$MyController {
  
  @override
  MyModel? build() {
    return ref.watch(modelListProvider).maybeWhen(
      //Accessing this state throws the error                             ↓
      data: (models) => models.singleWhereOrNull((model) => model.id == state?.id),
      orElse: () => null,
    );
  }
  
  @override 
  set state (MyModel value){
    state = value;
   }
}

I am calling

  ref.invalidate(modelListProvider); 

after changing data to trigger a rebuild but when I am reading the notifiers state again, I am getting an error:

StateError (Bad state: Tried to read the state of an uninitialized provider)

and the stacktrace leads me to the state of the notifier. How can I fix that?


Solution

  • This seems to work for now:

    @Riverpod(keepAlive:true)
    class MyController extends _$MyController {
      
      @override
      MyModel? build() {
       state = null;
       ref.listen(
         modelListProvider,
         (previous, next) {
           next.maybeWhen(
             data: (models) {
               state = models.firstWhereOrNull((model) => model.id == state?.id);
             },
             orElse: (){
               state = null;
             },
           );
         },
         fireImmediately: true,
       );
       return state;
      }
      
      @override 
      set state (MyModel value){
        state = value;
       }
    }