flutter - 无法在字段初始化程序中访问此内容以读取“属性”
问题描述
我正在尝试使用 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
}
请问,这是什么意思,我该如何纠正?谢谢
解决方案
我已经意识到我的错误,在构造函数中,我没有将构造函数参数断言为非空,而是在检查存储库的字段值。以下是来自的更正:
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());
** 表示在两个代码块中进行更改的位置。希望它也可以帮助某人。
推荐阅读
- python - 具有顺序和非顺序参数的 Psycopg2 查询
- java - Easymock 不保留方法的注释
- python - 验证 spark 数据框中的列名和数据类型
- python - num_epochs 在 eval_input_config TF2 对象检测 API v2 中是什么意思
- react-syntax-highlighter - 道具 lineNumberStyle 不会改变颜色
- reactjs - 使用 Redux Toolkit 调度多个异步操作
- javascript - Why Python django deployment in Heroku not executing ajax?
- postfix-mta - Postfix/Dovecot:无法接收外部电子邮件
- windows - 访问隐藏的 ini 文件部分(文件名上的冒号)
- r - R:ggplot 使用 facet_wrap 和 coord_flip 重新排序 x 轴