Search code examples
flutterdartriverpod

Flutter - Riverpod 2.0 - How to access onDispose callback?


I have this class

class EntryController {
  final TabController? tabController;
  final List<DictionaryEntry> history;

  EntryController({
    required this.history,
    this.tabController,
  });

  EntryController copyWith({
    TabController? tabController,
    List<DictionaryEntry>? history,
  }) {
    return EntryController(
      history: history ?? this.history,
      tabController: tabController ?? this.tabController,
    );
  }
}

And i have this Riverpod notifier

@riverpod
class ExpandedEntryController extends _$ExpandedEntryController {
  @override
  EntryController build() {
    return EntryController(
      history: [],
    );
  }

  void updateState(EntryController controller) => state = controller;

  void seeRelatedWord(DictionaryEntry relatedWord) {
    state.history.add(relatedWord);
    state.tabController!.animateTo(0);
  }

  void onDispose() {
    state.tabController!.dispose();
  }
}

I know that by default it has de autoDispose( ) method, but when it disposes i suppose i should dispose the tabController right? How should i do it?

Thanks


Solution

  • Correct your code like this:

    @riverpod
    class ExpandedEntryController extends _$ExpandedEntryController {
      @override
      EntryController build() {
    
        ref.onDispose(() {
          state.tabController?.dispose();
        });
    
        return EntryController(
          history: [],
        );
      }
    

    You can also use ref.watch or ref.listen safely in the build method of your notifier.