skip to Main Content

I would like to implement "Favorite" in my app, with a "favorite" icon inside a data card allowing the user to mark or unmark favorite. There is function to read the local db to see if the record is marked or not and displaying the corresponding icon.

Widget setFavouriteIcon(_id) {
  bool marked = markedFavourites(_id);
  if (marked == true) {
    return GestureDetector(
      onTap: (){
        addFavourites(_id);
      },
      child: Icon(
        size: 24,
        Icons.favorite_border_outlined,
        color: Colors.red,
      ),
    );
  }else{
    return GestureDetector(
      onTap: (){
        removeFavourites(_id);
      },
      child: Icon(
        size: 24,
        Icons.favorite,
        color: Colors.red,
      ),
    );
  }
}

markedFavourites() suppose is an async function to read the local db, but I got a compile error: A value of type ‘Future’ can’t be assigned to a variable of type ‘bool’.

How should I get a bool value from a future?

3

Answers


  1. Yep. you should use with .then() or async await to insert future value to variable.

    markedFavourites(_id).then((value)
         {bool marked = value}
    );
    

    Write like that.

    Login or Signup to reply.
  2. You can get response like :

    Future marked = await markedFavourites(_id);
    after that just check marked is null or not
    after that do same way you are using your code

    Login or Signup to reply.
  3. In order to get a bool value from your future returning function, you need to await it and your function needs to return a Future<bool> (future of type bool). Check out what your function return type is, and then await it in your code such as bool marked = await markedFavourites(_id);. And mark your setFavouriteIcon(_id) function async such as Widget setFavouriteIcon(_id) async {

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search