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
Yep. you should use with
.then()
orasync
await
to insert future value to variable.Write like that.
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
In order to get a
bool
value from your future returning function, you need toawait
it and your function needs to return aFuture<bool>
(future of type bool). Check out what your function return type is, and thenawait
it in your code such asbool marked = await markedFavourites(_id);
. And mark yoursetFavouriteIcon(_id)
functionasync
such asWidget setFavouriteIcon(_id) async {