首页 > 解决方案 > 无法在字段初始化程序中访问此内容以读取“属性”

问题描述

我正在尝试使用 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),
                                     ^^^^^^^^^^^

这是块构造函数:

class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationState> {

  final UserRepository _repository;
  AuthenticationBloc(UserRepositoryImpl repository)
  : assert(_repository != null), _repository = repository,
    super(AuthenticationStateInitial());

  ... other methods etc
 }

请问,这是什么意思,我该如何纠正?谢谢

标签: flutterauthenticationdependency-injectionrepository-patternbloc

解决方案


我已经意识到我的错误,在构造函数中,我没有将构造函数参数断言为非空,而是在检查存储库的字段值。以下是来自的更正:

final UserRepository _repository;
AuthenticationBloc(UserRepositoryImpl repository)
  : assert(**_repository** != null), _repository = repository, 
    super(AuthenticationStateInitial());

至:

final UserRepository _repository;
AuthenticationBloc(UserRepositoryImpl repository)
  : assert(**repository** != null), _repository = repository,
    super(AuthenticationStateInitial());

** 表示在两个代码块中进行更改的位置。希望它也可以帮助某人。


推荐阅读