【发布时间】:2021-08-15 07:07:24
【问题描述】:
我正在 Flutter 中为 Bloc Patter 实施 Null Safety,一切正常,但是当我尝试在我的小部件中实例化 bloc 时,出现错误“Null check operator used on a null value” 错误来自我的 bloc 事件的这一部分
class LoginEvent extends InheritedWidget{
final LoginBloc loginBloc = LoginBloc();
LoginEvent({required Widget child}) : super(child: child);
// This function has the error
static LoginBloc of(BuildContext context){
return context.dependOnInheritedWidgetOfExactType<LoginEvent>()!.loginBloc;
}
@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) => true;
}
如果我删除“!”出现的消息是“无法无条件访问属性'loginBloc',因为接收者可以为'null'。”
这是我的集体课
class LoginBloc with LoginState{
final _emailController = BehaviorSubject<String>();
final _passwordController = BehaviorSubject<String>();
Stream<String>get emailStream => _emailController.stream.transform(checkEmail);
Stream<String>get passwordStream => _passwordController.stream.transform(checkEmail);
Stream<bool> get formValidStream => Rx.combineLatest2(emailStream,passwordStream, (e,p) => true);
Function(String) get changeEmail => _emailController.sink.add;
Function(String) get changePassword => _passwordController.sink.add;
String get email => _emailController.value;
String get password => _passwordController.value;
dispose(){
_emailController.close();
_passwordController.close();
}
}
快速预览它的调用方式
@override
Widget build(BuildContext context) {
var height =
MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top;
var space = height > 650 ? DesignSpacings.spaceM : DesignSpacings.spaceS;
final bloc = LoginEvent.of(context); // if this line is commented the app shows the widget again
return Card(...);
}
【问题讨论】:
标签: flutter bloc dart-null-safety