skip to Main Content

// —– a list to store the favourites courses list

 List<FavouriteModel> _favCourses = [];

void initAddToFav(FavouriteModel model, BuildContext context) {
    if (_favCourses.contains(model)) {

      _courseController.removeFromFavourite(model);

      AlertHelper.showSanckBar(
          context, 'Remove from favourites !', AnimatedSnackBarType.error);

      notifyListeners();

    } else {

      _courseController.addToFavourite(model);

      AlertHelper.showSanckBar(
          context, 'Added to favourites !', AnimatedSnackBarType.success);

      notifyListeners();
    }
  }

When try check _favCourses.contains favourite model then if condition not working even data exsist else part working

2

Answers


  1. You are using .contains on a list of FavouriteModel objects. Dart doesn’t automatically know how to test if one object is equal to another in the same way that it compares numbers or strings. So it will compare the item by memory address. That is unless you tell it how to test if the two objects are equal using a key.

    Take a look at this answer here which uses a different way of checking if the list contains the item.

    Check whether a list contain an attribute of an object in dart

    Login or Signup to reply.
  2. you are check wrong condition because you applied the condition on _favCourses list and perform the task in _courseController.

    Correct your if condition
    
    If(_courseController.contains(model))
      {
         _courseController.removeFromFavourite(model);
         AlertHelper.showSanckBar(context, 'Remove from favourites !', AnimatedSnackBarType.error);
    
      notifyListeners();
      }
       
    
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search