我正在尝试从Async函数获取该值,该函数返回一个整数,然后该整数用于设置UI中小部件的颜色。
异步功能:
// Returns a future<int> instead of an int due to async
Future<int> getLikeStatus(String name) async {
int likeStatus =
await getLikeStatusFromPostLikes(name); // this returns an int
return likeStatus;
}
下游用法:
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
InkWell(
child: IconButton(
icon: Icon(Icons.thumb_up),
color: getLikeStatus(snapshot.data[index].name) == 1
? Colors.green
: Colors.blue) // cannot use future here
),
],
);
如何返回likeStatus
变量以用于我的小部件中的color
属性?
在这种情况下,您可以使用FutureBuilder
。它需要一个FutureBuilder
值,并使您能够传递future
,当您将来的状态更新时,该builder
将被调用:
FutureBuilder(
future: getLikeStatus(snapshot.data[index].name),
builder: (context, snapshot) {
if (!snapshot.hasData) return Container(); // You can indicate that you are loading the data here.
return IconButton(
icon: Icon(Icons.thumb_up),
color: snapshot.data == 1
? Colors.green
: Colors.blue,
);
},
)