Flutter 颤振-未来<;布尔>;转换成布尔
我有一个未来的布尔方法,我想用这个方法IconButton颜色。如果我使用以下代码,我会在设备屏幕上看到一条错误消息类型“Future”不是类型转换中类型“bool”的子类型。Flutter 颤振-未来<;布尔>;转换成布尔,flutter,dart,boolean,Flutter,Dart,Boolean,我有一个未来的布尔方法,我想用这个方法IconButton颜色。如果我使用以下代码,我会在设备屏幕上看到一条错误消息类型“Future”不是类型转换中类型“bool”的子类型。 Future<bool> ifExistInFavoriteList(String url) async { } } 是,因为ifExistInFavoriteList(字符串url)的类型为Future,您需要使用FutureBuilder小部件来获取bool值 Expanded( child
Future<bool> ifExistInFavoriteList(String url) async {
}
}
是,因为
ifExistInFavoriteList(字符串url)
的类型为Future
,您需要使用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
},
);
},),
),
你不能简单地把未来打给布尔。您需要使用wait或then语法从未来获取bool值。但我建议你使用a,这将是最好的解决方案
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
},
);
},
),
一般性的回答
假设这是返回Future
的函数
Future myFunc()async=>true;
要从中获取bool
值
异步等待
void main()异步{
var value=wait myFunc();//value=true
}
然后使用:
void main(){
布尔值;
myFunc()。然后((结果)=>value=result);
}
这很有魅力!这就是我想要的。。非常感谢。如果我这样使用,图标颜色不会改变。你能更新你的密码吗。onPressed:(){if(snapshot.hasData&&snapshot.data){deleteFromFavoriteList(widget.imageUrl);}else{saveFavoriteList(widget.imageUrl);}如果我想在onPressed中编写一个方法,IconColor not changed:(想想instagram中的like按钮。@jancooth请检查此线程:
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
},
);
},),
),
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
},
);
},
),