我正在尝试从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;
}
岗位职能:
Future <List<dynamic>> fetchData() async {
// Some code to make GET request to private server with data and push as posts
final response = await posts.get();
final result = response.map((m) => Post.fromJson(m)).toList();
return result;
}
下游使用-使用上述
post
函数:// snapshot is populated by post future in FutureBuilder
child: FutureBuilder<List<dynamic>>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
...
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
,则可以将其作为单个将来的函数(fetchAll
),如下所示:
post = fetchAll();
....
Future<Map<Post, int>> fetchAll() async {
final posts = await fetchData();
final result = <Post, int>{};
for(final x in posts){
final status = await getLikeStatus(x.name);
result[x] = status;
}
return result;
}
Future <List<Post>> fetchData() async {
// Some code to make GET request to private server with data and push as posts
final response = await posts.get();
final result = response.map((m) => Post.fromJson(m)).toList();
return result;
}
// 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;
}
...
child: FutureBuilder<Map<Post, int>>(
future: post, //TODO: `fetchAll` instead of `fetchData`
builder: (context, snapshot) {
if (snapshot.hasData) {
//Since snapshot is a map you can get `Post` data using `snapshot.data.entries.elementAt(index)`
...
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
InkWell(
child: IconButton(
icon: Icon(Icons.thumb_up),
color: snapshot.data.entries.elementAt(index).value
? Colors.green
: Colors.blue) // cannot use future here
),
],
),
//...
}
},
),
在获取状态请求上方,一个接一个地发送。因此,如果名称列表很大,可能会花费很长时间。您可以像这样并行处理
Future<Map<Post, int>> fetchAll() async {
final posts = await fetchData();
final result = <Post, int>{};
final statusList =
await Future.wait<int>(posts.map((x) => getLikeStatus(x.name)));
for (int i = 0; i < posts.length; i++) {
result[posts[i]] = statusList[i];
}
return result;
}
关于flutter - 如何从异步功能使用Future?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59826446/