Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter - Future<bool> convert to bool

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
                        },
                      ),
                    )
like image 619
jancooth Avatar asked Jun 17 '26 14:06

jancooth


1 Answers

A general answer.

Say this is your function which returns Future<bool>.

Future<bool> myFunc() async => true;

To get the bool value from it,

  1. Use async-await

    void main() async {
      var value = await myFunc(); // value = true
    }
    
  2. Use then:

    void main() {
      bool? value;
      myFunc().then((result) => value = result);
    }
    
like image 170
CopsOnRoad Avatar answered Jun 20 '26 12:06

CopsOnRoad