Reputation: 671
Case: New to riverpod - trying to migrade from regular flutter provider.
To create a StateNotifierProvider in riverpod one has to give it an instance that extends StateNotifier.
i.e.:
class SomeModel extends StateNotifier {};
StateNotifierProvider<SomeModel> someModelProvider = StateNotifierProvider<SomeModel>((ref) => someModel());
All well and good, if you have a simple model class. In my case, my model class is layered and extends a lower class:
class SomeModel extends SomeLowerClass ...
I can't extend StateNotifier - I'm already extending some lower class. I can't use 'with' for either class because they both have constructors.
This seems like a an onerous limitation. Is there a way to create a provider that uses a model that extends another class besides 'StateNotifier', or use 'StateNotifier' in some other way other than by extending?
(puzzled, already...)
Upvotes: 1
Views: 1764
Reputation: 671
Ok, the issue, of course, is my misconceptions.
@yeasin_shiekh is correct, I believe - what I'm (finally) getting is that StateNotifier contains an immutable object (not object extending StateNotifier). That immutable object can be constructed however, but the StateNotifier sends a notification when that object is replaced (not changed).
In my case, my model is a large, mutable object. So StateNotifier is not the correct thing to use. "ChangeNotifier" is what I need (and what I had used with flutter provider). The model then "extends" the ChangeNotifier (or you can use "with" if the model extends something else - my case) and you call "notifyListeners()" explicitly on changes, as before.
Getting the distinctions more clearly...
Upvotes: 0
Reputation: 5601
2 options:
SomeLowerClass should be extending StateNotifier
class SomeLowerClass extends StateNotifier {
SomeLowerClass() : super(0); ///or whatever your state should be
///some other methods
}
class SomeModel extends SomeLowerClass {}
SomeLowerClass is an abstract class for you to implement
abstract class SomeLowerClass {
void myMethod();
....
}
class SomeModel extends SomeLowerClass implements SomeLowerClass{
@override
void myMethod() {}
}
I think option 1 is what you really want to do
Upvotes: 0