skip to Main Content

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

2

Answers


  1. Don’t override this.onDispose()!. Add

    ref.onDispose(() => state.tabController?.dispose());
    

    to your build(). That should take care of disposing that controller when this controller goes away.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search