flutter “错误状态:尝试在侦听futureprovider时使用riverpod读取未初始化的提供程序的状态”

42fyovps  于 2023-04-07  发布在  Flutter
关注(0)|答案(1)|浏览(135)

我有这个生成的通知程序,它应该在数据更改时重建,而不会在重建时丢失对先前选定对象的引用。

@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;
   }
}

我在打电话

ref.invalidate(modelListProvider);

在更改数据以触发重建后,但当我再次阅读通知程序状态时,我收到一个错误:
StateError (Bad state: Tried to read the state of an uninitialized provider)
堆栈跟踪将我引导到通知程序的状态。我该如何解决这个问题?

zc0qhyus

zc0qhyus1#

现在看来,这是可行的:

@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;
   }
}

相关问题