【发布时间】:2021-05-18 06:31:21
【问题描述】:
我正在尝试使用 bloc 模式和存储库对用户进行身份验证。我还使用GetIt 注入了一些我的依赖项,如下所示:
final getItInstance = GetIt.I;
Future init(){
getItInstance.registerLazySingleton<APIClient>(() => APIClient());
getItInstance.registerLazySingleton<UserRemoteDataSource>(
() => UserRemoteDataSourceImpl(client: getItInstance()));
// commented out previously, getItInstance.registerLazySingleton<UserRepository>(
() => UserRepositoryImpl(dataSource: getItInstance()));
}
错误的UserRepository 类的实现是:
abstract class UserRepository {
Future<UserModel> loginUser(Map<String, dynamic> body);
Future<UserModel> registerUser(Map<String, dynamic> body);
Future<UserModel> getCurrentUser();
Future<void> logOut();
}
UserRepositoryImpl 类只是实现上述方法并通过 http 连接远程数据源的包装器,因此已省略。从 DI 类中可以很容易地看到依赖项和依赖项,为了简洁起见,我省略了它们。
现在,在我的 auth bloc 中,我试图将 UserRepository and UserRepositoryImpl 传递给 bloc 构造函数,以方便 api 调用,但出现此错误:
lib/presentation/blocs/authentication/authentication_bloc.dart:18:42: Error: Can't access 'this' in a field initializer to read '_repository'.
: _repository = repository, assert(_repository != null),
^^^^^^^^^^^
这是 bloc 构造函数:
class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationState> {
final UserRepository _repository;
AuthenticationBloc(UserRepositoryImpl repository)
: assert(_repository != null), _repository = repository,
super(AuthenticationStateInitial());
... other methods etc
}
请问这是什么意思,我该如何纠正?谢谢
【问题讨论】:
标签: flutter authentication dependency-injection repository-pattern bloc