1

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

1 Answers1

2

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.

Mehmet Ali Bayram
  • 7,222
  • 2
  • 22
  • 27
  • 3
    Good 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](https://stackoverflow.com/a/67990442/421195), and [Flutter Campus: Null check operator used on a null value](https://www.fluttercampus.com/guide/225/null-check-operator-used-on-a-null-value/) – paulsm4 Jan 06 '22 at 19:24
  • @paulsm4 thank you very much – Mehmet Ali Bayram Jan 06 '22 at 20:23