i want return type of this method bool and depende on i rendered the UI
global variable bool checkFav = false;
on every Page View i want to call this method for appearing the favourite icon
Future<bool?> checkFavourite(int id) async {
final url = Uri.parse('https://quotes.limpidsol.com/api/favourite');
var pref = await SharedPreferences.getInstance();
final response = await http.post(
url,
body: {'qoute_id': id.toString()},
headers: {"Authorization": "Bearer ${pref.getString('token')}"},
);
if (response.statusCode == 200) {
final Map<String, dynamic> responseData = jsonDecode(response.body);
String message = responseData['message'];
if (message == 'Qoute favourite successfully') {
print('ok');
return true;
}
}
return null;
}
method call in pageView::>>
checkFav = checkFavourite(quote_id) as bool;
depending the returning value of future (true/ false)
i updating the UI without loading
IconButton(
onPressed: () {
checkFav
? handleRemoveToFav(quoteList[index]['id'])
: handleAddToFav(quoteList[index]['id']);
},
icon: Icon(
checkFav
? Icons.favorite_outlined
: Icons.favorite_border,
color: checkFav ? Colors.red : Colors.grey,
size: 30.0,
),
),
FutureBuilder return something widget or progressIndicator but scanrio is different please view the picture
please view picture
3
Answers
checkFavourite add/remove methods
<>
IconButton( onPressed: () { checkFav ? handleRemoveToFav(quoteList[index]['id']) : handleAddToFav(quoteList[index]['id']); }, icon: Icon( checkFav ? Icons.favorite_outlined : Icons.favorite_border, color: checkFav ? Colors.red : Colors.grey, size: 30.0, ), ),
Since your method returns a
Future
, you mustawait
it. So you need to docheckFav = await checkFavourite(quote_id)
instead ofcheckFav = checkFavourite(quote_id) as bool
You can use a FutureBuilder to show a gray favorite icon until the
checkFavourite
method completes, and then based on the returned result you will show gray or red icon.If you are not OK, with this approach, because of the icon "blink", you can delay the render of the whole build method until you fetch the favorite state.
You can show a
CircularProgressIndicator
, until data is loaded, then show your widgets