Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have a problem with Null Safety an the problem is 'Null check operator used on a null value'

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!;

>Solution :

In order your error message and your code you used null check operator ! in 2 fields;

  1. 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()));
});
  1. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading