Home > database >  Problem related to null safety: A nullable expression can't be used as a condition
Problem related to null safety: A nullable expression can't be used as a condition

Time:07-19

I encountered this error regarding null safety and I could not solve it

HomeModel? homeModel;

  Map<int, bool> favorites = {};

  void getHomeData() {
    emit(ShopLoadingHomeDataState());

    DioHelper.getData(
      url: HOME,
      token: token,
    ).then((value) {
      homeModel = HomeModel.fromJson(value?.data);

      printFullText(homeModel!.data!.banners[0].image!);
      print(homeModel?.status);
      
      homeModel!.data!.products.forEach((element) {
        favorites.addAll({
          element.id! : element.inFavorites!,
        });
      });

      emit(ShopSuccessHomeDataState());
    });

Here, an error occurs

backgroundColor: ShopCubit.get(context).favorites[model.id] ? defaultColor : Colors.grey ,

And say :

"A nullable expression can't be used as a condition. Try checking that the value isn't 'null' before using it as a condition."

And:

"Error: A value of type 'bool?' can't be assigned to a variable of type 'bool' because 'bool?' is nullable and 'bool' isn't"

please help me

CodePudding user response:

The problem is that the return of a map by a key, i.e. map[key], will always have null attached to it because the value could not exist for the provided key.

To fix it default the value to something else if the model.id is not in the favorites map with the ?? operator like the following:

backgroundColor: ShopCubit.get(context).favorites[model.id] ?? false  // <- Here
  ? defaultColor 
  : Colors.grey,

Or, if the value exists for sure, just force it to be non-null with the postfix ! operator. But take care as the value should exist otherwise an exception is thrown.

backgroundColor: ShopCubit.get(context).favorites[model.id]!  // <- Here
  ? defaultColor 
  : Colors.grey,

CodePudding user response:

The defaultColor must have been added like

Color? defaultColor = Colors.red;

make it

Color defaultColor = Colors.red;

remove the ? after Color

Edit

backgroundColor: ShopCubit.get(context).favorites[model.id] == null || ShopCubit.get(context).favorites[model.id] == true ? defaultColor : Colors.grey 

  • Related