It happened when getting some data from firebase and decoding them using model, and here is the method:
UserModel? userModel;
void getUser() {
emit(GetUserLoadingsState());
FirebaseFirestore.instance.collection('users').doc(uId).get().then((value) {
userModel = UserModel.fromJson(value.data()!);
emit(GetUserSuccessState());
}).catchError((error) {
emit(GetUserErrorState(error.toString()));
});
}
Calling the method
return BlocProvider(
create: (BuildContext context) => AppCubit()..getUser(),
child: BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: lightTheme,
home: startWidget,
);
},
),
);
and consumer
BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
var user = AppCubit.get(context).userModel!;
In order your error message and your code you used null check operator !
in 2 fields;
UserModel? userModel;
void getUser() {
emit(GetUserLoadingsState());
FirebaseFirestore.instance.collection('users').doc(uId).get().then((value) {
if (value.exists) {
userModel = UserModel.fromJson(value.data()!);
emit(GetUserSuccessState());
}
}).catchError((error) {
emit(GetUserErrorState(error.toString()));
});
BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
if (AppCubit.get(context).userModel != null)
var user = AppCubit.get(context).userModel!;
You shouldn't use the !
null check operator unless you know that your value is not null.