Semih Yilmaz
Semih Yilmaz

Reputation: 618

boolean expression must not be empty error in Flutter

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);
                    },
                  ),

Upvotes: 0

Views: 133

Answers (2)

Yauheni Prakapenka
Yauheni Prakapenka

Reputation: 1714

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: () {},
  );
}

Upvotes: 0

julemand101
julemand101

Reputation: 31219

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

Upvotes: 2

Related Questions