简体   繁体   中英

Can a abstract class have a method with a return type of another abstract class?

My flutter/dart app uses the Provider package with various authentication services such as Google, Apple, Firebase, etc. I want my abstract classes to provide more direction for the various implementations, like this:

abstract class AuthService{
    Future<User> signIn();
}

abstract class User{}

In reality, I have to implement it as:

abstract class AuthService{
    Future<dynamic> signIn();
}

because my specific implementations of AuthService won't return a User, but FirebaseUser or AppleUser. Is there a way to have the return type specified as some kind of implementation of my abstract User class?

This isn't really any different from returning any kind of abstract base class; construct an instance of a concrete class and return it.

abstract class AuthService{
    Future<User> signIn();
}

abstract class User{}

class FirebaseUser extends User {}

class FirebaseAuthService extends AuthService {
  @override
  Future<User> signIn() {
    return Future.value(FirebaseUser());
  }
}

abstract class AuthService<T>{
    Future<T> signIn();
}

class ExampleAuthService extends AuthService<FirebaseUser> {
  @override
  Future<FirebaseUser> signIn() {
    throw UnimplementedError();
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM