type 'Null' is not a subtype of type 'bool' in type cast

Issue

I have Created a Map<String,bool>(in which the key are of type String and the values are of type Boolean) in flutter and When I want to use the bool values in if condition it give me error saying "A nullable expression can’t be used as a condition.
Try checking that the value isn’t ‘null’ before using it as a condition."
When I use "as bool" then the error is gone but the program is not executed properly and give me the error in the pic

//this is the code
 Map<String, bool> _userFilters = {
"gluten": false,
"lactose": false,
"vegan": false,
"vegetarian": false,
 };
  List<Meal> filteredMeal = DUMMY_MEALS;
  void saveFilters(Map<String, bool> filteredData) {
    setState(() {
      _userFilters = filteredData;
      filteredMeal = DUMMY_MEALS.where(
        (meal) {
          if (_userFilters['gluten']as bool) { // _userFilter['gluten'] is giving error
            return false;
          }
          if (_userFilters['lactose']as bool) {
            return false;
          }
          if (_userFilters['vegan']as bool) {
            return false;
          }
          if (_userFilters['vegetarian'] as bool) {
            return false;
          }
          return true;
        },
      ).toList();
    });
  }

enter image description here

Solution

No need to cast your map entries to booleans. use an exclamation mark at the end of your variable (e.g, _usedFilters['gluten']!) to treat it as non-nullable.

Rewrite all your conditions like this (if you’re sure that the value won’t be null):

    if (_userFilters['gluten']!) {
      return false;
    }
    if (_userFilters['lactose']!) {
      return false;
    }
    if (_userFilters['vegan']!) {
      return false;
    }
    if (_userFilters['vegetarian']!) {
      return false;
    }

From Dart.dev:

“Casting away nullability” comes up often enough that we have a new
shorthand syntax. A postfix exclamation mark (!) takes the expression
on the left and casts it to its underlying non-nullable type.

Answered By – Amirhossein Shahbazi

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *