I am facing this weird issue, where though I have set the state, but the value when accessed in init state is showing null !!
user_cubit.dart
UserCubit() : super(UserInitialState()) {
emit(UserMainLoadingState());
_firestore
.collection("users")
.doc(_currentUser?.uid)
.snapshots()
.listen((event) {
event.exists
? {
emit(UserExists(
userModel: UserModel.fromjson(event.data()!, event.id)))
}
: {print("There is no such user"), emit(UserNotExists())};
});
}
user_state.dart
class UserState extends Equatable {
final UserModel? userModel;
const UserState({this.userModel});
@override
List<Object?> get props => [userModel];
}
class UserExists extends UserState {
UserExists({required UserModel userModel}) : super(userModel: userModel) {
print("I am inside the UserExists state and the user is :$userModel");
}
}
myWidget.dart
@override
void initState() {
_userState = const UserState();
print("I am inside the initState The value of userstate is ${_userState.userModel}"); // This prints null , but why ?
if (_userState.userModel != null) {
print("user is ${_userState.userModel.toString()}");
}
super.initState();
}
Console log:
I/flutter ( 5029): I am inside the UserExists state and the user is :avatar boy
I/flutter ( 5029): fullName krrrt
I/flutter ( 5029): dob 19/1/2022
I/flutter ( 5029): email [email protected]
I/flutter ( 5029): phone 12222222255
I/flutter ( 5029): I am inside the initState The value of userstate is null
Though the userState's
userModel
has value, why can't i access that in the initState
.
// Ignore this, this is for stackoverflow.
// Ignore this, this is for stackoverflow.
// Ignore this, this is for stackoverflow.
// Ignore this, this is for stackoverflow.
// Ignore this, this is for stackoverflow.
To access the state of a BLoC or Cubit in Flutter, you can use the
context.read<Bloc>()
. This method returns a Bloc instance that you can use to access the current state.