Home > OS >  Flutter, how to implement "Favorites" with local db
Flutter, how to implement "Favorites" with local db

Time:02-02

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?

CodePudding user response:

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 {

CodePudding user response:

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

CodePudding user response:

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.

  • Related