Search code examples
flutterblocdart-null-safetycubitnull-safety

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

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.