Search code examples
flutterdartoverridingabstract-class

How to use ChangeNotifier with a abstract class in Flutter?


In my dart application, I wanted to use ChangeNotifier for my authentication class.

I have an abstract class and another class implements the methods.

abstract class AuthBase {
  Future<void> signIn(String email, String password);
  Future<void> signUp(String email);
  Future<void> signOut();
}

class Auth with ChangeNotifier implements AuthBase {
...
}

As you can see ChangeNotifier is not used with the base class.

What I would like to do is use ChangeNotifier with the abstract class. But not sure how to override the methods in Auth class;

@override
  void addListener(listener) {
    // TODO: implement addListener
  }

  @override
  void dispose() {
    // TODO: implement dispose
  }

  @override
  // TODO: implement hasListeners
  bool get hasListeners => throw UnimplementedError();

  @override
  void notifyListeners() {
    // TODO: implement notifyListeners
  }

  @override
  void removeListener(listener) {
    // TODO: implement removeListener
  }

Can someone provide some help with this?


Solution

  • Provider documentation has an example for that case: https://github.com/rrousselGit/provider#can-i-consume-an-interface-and-provide-an-implementation

    abstract class ProviderInterface with ChangeNotifier {
      ...
    }
    
    class ProviderImplementation with ChangeNotifier implements ProviderInterface {
      ...
    }
    
    class Foo extends StatelessWidget {
      @override
      build(context) {
        final provider = Provider.of<ProviderInterface>(context);
        return ...
      }
    }
    
    ChangeNotifierProvider<ProviderInterface>(
      create: (_) => ProviderImplementation(),
      child: Foo(),
    ),