0

I'm trying to check if the user likes the current post and set an icon. I'm trying to do a simple check but it throws an error.

The method I created

List<String> fav = List<String>();

checkFav(String id) {
    bool isFav = fav.contains(id);

    if(isFav)
      return true;
    else
      return null;
  }

And where I use the method



IconButton(
           icon: Icon(favorite.checkFav(widget.blogModel.id)
               ? Icons.favorite
               : Icons.favorite_border,
                 color: Colors.redAccent),

                    onPressed: () {
                      setState(
                        () {
                          favorite.checkFav(widget.blogModel.id)
                              ? favorite.deleteItemToFav(widget.blogModel.id)
                              : favorite.addItemToFav(widget.blogModel.id);
                        },
                      );
                      //favorite.checkItemInFav(widget.blogModel.id, context);
                    },
                  ),

2 Answers 2

2

Your checkFav should specify it returns bool. Also, you are returning null in case of false which is properly not what you have intended.

So you can rewrite your method to the following which will properly work:

bool checkFav(String id) => fav.contains(id);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes the error is gone but the icon still does not change
@SemihYılmaz Well, that is an entire different issue which is not even part of your question. Please make another question for that problem,
0

Good day. Try this code:

class MyHomePage extends StatelessWidget {
  final _favorites = <String>['1', '2', '3'];

  @override
  Widget build(BuildContext context) {
    final buttonIsActive = checkFavorites('1', _favorites);
    return Scaffold(
      body: Center(
        body: Center(child: buildFavoriteButton(isActive: buttonIsActive)),
       ),
    );
  }
}

bool checkFavorites(String id, List<String> favorites) {
  return favorites.contains(id);
}

Widget buildFavoriteButton({bool isActive = false}) {
  return IconButton(
    icon: Icon(
      Icons.ac_unit,
      color: isActive ? Colors.red : Colors.grey,
    ),
    onPressed: () {},
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.