如何从异步功能使用Future?

问题描述 投票:1回答:1

我正在尝试从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属性?

flutter dart flutter-layout
1个回答
0
投票

在这种情况下,您可以使用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,
        );
  },
)
© www.soinside.com 2019 - 2024. All rights reserved.