I have an auth package in my Flutter app that defines the BaseUser class. The BaseUser class provides the basic structure for a User class which is defined inside an app. Here is how the BaseUser class looks:
class BaseUser {
final String id;
final String email;
BaseUser({ required this.id, required this.email });
}
In addition to the BaseUser class, my package also defines UserAPIService which make login, signup, etc. requests.
class UserAPIService extends BaseAPIService {
Future<LoginResponse> login({ required String email, required String password }) async {
final response = await api.login(email, password);
LoginResponse loginResponse = LoginResponse.fromJSON(response);
return loginResponse;
}
}
This is how LoginResponse looks like:
class LoginResponse {
final BaseUser user;
factory LoginRespionse.fromJSON(Map<String, dynamic>) {
// Error handle logic...
return LoginResponse(
user: BaseUser(email: json['user']['email'], id: json['user']['id']);
);
}
}
BaseAPIService is a simple abstract class containing the function declarations for login, signup, etc.
All these services are used in the AuthenticationRepository inside the app, somehow like this:
class AuthenticationRepository {
Future<LoginResponse> login(String email, password) {
final response = userApiService.login(email, password);
return response;
}
}
This is the User class defined inside the app:
class User extends BaseUser {
final String? fullName;
User({
required super.email,
required super.id,
this.fullName,
});
// Named constructors and other methods...
}
PROBLEM: How can I make the user class defined inside the app type compatible with the BaseUser which is defined in LoginResponse class?
Also, Is it possible to somehow inject the User class in the LoginResponse class so that the named constructor of the User class is called when parsing the user?
Maybe you can create a Use Case
class UserUseCase {
User convertLoginResponseToUser(LoginResponse loginResponse) {
return User(id: loginResponse.user.id, email: loginResponse.user.email, fullName: null);
}
}
Then in your class that call AuthenticationRepository
Future<User> login(String email, password) async {
final response = await authenticationRepository.login(email, password);
return userUseCase.convertLoginResponseToUser(response);
}
If LoginResponse is in external package, it should not know about your User
BaseUser = Data Layer
AuthenticationRepository = Data Layer
User = Domain Layer (Entity)
UserUseCase = Domain Layer (Use Case)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With