I'm implementing Null Safety to Bloc Patter in flutter, everything was ok, but when I tried to instance bloc in my widgets, I got an error "Null check operator used on a null value"
The error cames from this section on my bloc event
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;
}
If I delete the '!' the message that appears is "The property 'loginBloc' can't be unconditionally accessed because the receiver can be 'null'."
This is my bloc class
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();
}
}
Fast preview of how it is called
@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(...);
}