flutter - Future<bool> convert to bool
Solution 1
You can't just simply typecast a Future to bool. Either you need to use await or then syntax to get the bool value from that future. But I suggest you to use a FutureBuilder, which will be the best solution.
FutureBuilder(future: ifExistInFavoriteList(widget.imageUrl),
builder:(context, snapshot) {
Color iconColor = Colors.green;
if (snapshot.hasData && snapshot.data) {
iconColor = Colors.purple;
}
return IconButton(color: iconColor,
icon: Icon(Icons.category),
onPressed: () {
//TO-DO
},
);
},
),
Solution 2
Yes because ifExistInFavoriteList(String url)
is of type Future<bool>
, you need to use FutureBuilder widget to get the bool value.
Expanded(
child: FutureBuilder(
future: ifExistInFavoriteList(widget.imageUrl),
builder: (context, asyncSnapshot){
if(asyncSnapshot.hasData){
final _isLiked = asyncSnapshot.data;
return IconButton(
color:
_isLiked() ? Colors.deepPurple : Colors.green,
icon: Icon(Icons.category),
onPressed: () {
//TO-DO
},
);
}
return IconButton(
color:Colors.grey,
icon: Icon(Icons.category),
onPressed: () {
//TO-DO
},
);
},),
),
Solution 3
A general answer.
Say this is your function which returns Future<bool>
.
Future<bool> myFunc() async => true;
To get the bool
value from it,
-
Use
async-await
void main() async { var value = await myFunc(); // value = true }
-
Use
then
:void main() { bool? value; myFunc().then((result) => value = result); }
jancooth
Updated on December 18, 2022Comments
-
jancooth over 1 year
I have a future bool method and i want to use this method IconButton color. If i use below codes, i see a error message on my device screen type'Future' is not a subtype of type 'bool' in type of cast.
Future<bool> ifExistInFavoriteList(String url) async {
bool ifExists = false;
SharedPreferences prefs = await SharedPreferences.getInstance(); List my = (prefs.getStringList('myFavoriteList') ?? List());
my.contains(url) ? ifExists = true : ifExists = false;
return ifExists;
}
bool _isLiked() { bool a = false; a = ifExistInFavoriteList(widget.imageUrl) as bool; return a;
} }
Expanded( child: IconButton( color: _isLiked() ? Colors.deepPurple : Colors.green, icon: Icon(Icons.category), onPressed: () { //TO-DO }, ), )