Search code examples
flutterinheritanceflutter-provider

How can I use different child classes as providers in flutter?


I have the interface of an API using an abstract class and multiple implementations aka child classes.

abstract class API extends ChangeNotifier {
    void foo();
}

class TestAPI extends API {
  @override
  void foo() {
    // do something
  }


class RealAPI extends API {
  @override
  void foo() {
    // do something else
  }

Now I want to be able to switch those different implementations as providers without redeclaring all my dependent widgets. So they use the parent class:

Provider.of<API>(context)

I tried using this

ChangeNotifierProvider(
    create: (context) => TestAPI(),// RealAPI()
    child: // ...

but then flutter can't find my provider

Could not find the correct Provider<API> above this Widget


Solution

  • You just need to specify the type of provider flutter should look for. So pass in the parent class there:

    ChangeNotifierProvider<API>( // notice the type here
        create: (context) => TestAPI(),
        child: // ...
    )