флаттер - будущее <bool>конвертировать в bool - PullRequest
0 голосов
/ 24 марта 2020

У меня есть будущий метод bool, и я хочу использовать этот метод IconButton color. Если я использую приведенные ниже коды, я вижу сообщение об ошибке на экране моего устройства тип «Будущее» не является подтипом типа «bool» в типе приведения.

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;

вернуть 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
                        },
                      ),
                    )

Ответы [ 2 ]

1 голос
/ 24 марта 2020

Вы не можете просто типизировать Будущее, чтобы кипеть. Либо вам нужно использовать await или затем синтаксис, чтобы получить значение bool из этого будущего. Но я предлагаю вам использовать FutureBuilder , который будет лучшим решением.

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
                      },
           );
     },
),
1 голос
/ 24 марта 2020

Да, поскольку ifExistInFavoriteList(String url) имеет тип Future<bool>, вам нужно использовать виджет FutureBuilder для получения значения bool.

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
            },
          );
      },),
    ),
...