将来<bool>转换为布尔值



我有一个未来的bool方法,我想使用这个方法IconButton颜色。如果我使用以下代码,我会在设备屏幕上看到一条错误消息类型"Future"在类型转换中不是类型"bool"的子类型

Future<bool> ifExistInFavoriteList(String url) async {

bool ifExists=false;

SharedPreferences prefs=等待SharedPreferences.getInstance((;列出my=(prefs.getStringList('myFavoriteList'(??List(((;

我的.包含(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
},
),
)

一般答案。

假设这是返回Future<bool>的函数。

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

要从中获得bool值,

  1. 使用async-await

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

    void main() {
    bool? value;
    myFunc().then((result) => value = result);
    }
    

不能简单地将Future类型转换为bool。您需要使用wait或then语法来获取将来的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
},
);
},
),

是的,因为ifExistInFavoriteList(String url)的类型是Future<bool>,所以需要使用FutureBuilder小部件来获取布尔值。

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

最新更新