I have a problem with Null Safety an the problem is 'Null check operator used on a null value'
300
In order your error message and your code you used null check operator !
in 2 fields;
- Field should be like this;
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()));
});
- Field should be like this;
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.
Author by
Alaa Elsweedy
Updated on December 01, 2022Comments
-
Alaa Elsweedy over 1 year
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!;
-
Alaa Elsweedy over 2 yearsI get data from firebase successfully but when using the user model the error happened.
-
-
paulsm4 over 2 yearsGood reply - and probably exactly the solution I'd recommend. I'd encourage the OP to explore other alternatives as well, including Null check operator used on a null value, and Flutter Campus: Null check operator used on a null value
-
Mehmet Ali Bayram over 2 years@paulsm4 thank you very much