'autoDispose modifier in riverpod

I have multiple values (in class) in provider and when I use the autoDispose modifier in provider then I want to dispose of only a few values in the provider is it possible to do like this?

I have searched for this on the internet but I didn't find any resources related to this requirement.

final provider = StateProvider((ref) => LoginDetails(
      errorMessage: '', status: 0));

class LoginDetails {
  int status;
  String errorMessage;
  LoginDetails({
    required this.status,
    required this.errorMessage,
  });

  LoginDetails copyWith({
    int? status,
    String? errorMessage,
  }) =>
      LoginDetails(
        status: status ?? this.status,
        errorMessage: errorMessage ?? this.errorMessage,
      );
}


Solution 1:[1]

There is no way to have autoDispose only dispose a few property. autoDispose is all or nothing

On the other hand, using version 2.0.0-dev, you can use ref.onCancel to perform some logic when the last listener is removed – which is available even on providers that are not autoDispose

So you can do:

final provider = Provider((ref) {
  ref.onCancel(() {
    // TODO reset the few properties of your choice
  });

  return SomeState();
});

Solution 2:[2]

I know two ways to do that

The first way is to make the variables private static

  static int _status = 0;
  
  // You can access it outside the Provider class by using getter
  int get status => _status;

The second way is to have another provider that contains the needed information which you don't want to lose, and I prefer this way.

and still I am sure there is many alternative solutions out there but it's all depends on your use case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rémi Rousselet
Solution 2 Mohammed Alfateh