【问题标题】:Unable to Access This in a Field Initializer to Read 'property"无法在字段初始化程序中访问此内容以读取“属性”
【发布时间】: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


    【解决方案1】:

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

    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());
    

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

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 2019-11-20
      相关资源
      最近更新 更多