How to use Provider with Base Class in Flutter/Dart

Viewed 768

I have base and derived classes like this:

abstract class A extends ChangeNotifier{....}
class B extends A{....}

I am using provider like this:

ChangeNotifierProvider<B>(create: (context) => B())

and accessing using both A and B(depending on situation) like this:

Provider.of<A>(context) //This does not work. Why?
Provider.of<B>(context) //This works.

How do I correctly use base class with Provider.of i.e. Provider.of<A>(context)?

Edit: The ChangeNotifierProvider is only for B. I do not have a provider for A. But, I want to access using A as A is the base class of B.

1 Answers

You'll have to do something like this:

final b = B();
ChangeNotifierProvider<A>.value(value: b)
ChangeNotifierProvider<B>.value(value: b)

Then you can access your B class by using either:

Provider.of<A>(context) //This now works.
Provider.of<B>(context) //This works.
Related