flutter - 如何从异步功能使用Future?

标签 flutter dart flutter-layout

我正在尝试从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/

相关文章:

dart - 用于 Flutter/Dart 的 Google Sheets API v4

Dart PolymerElement 事件总线

Flutter 行文本溢出

flutter - 如何在渲染之前获取文本小部件的宽度

Flutter:listTile 中的 Navigator.push 不起作用

flutter - 如何将我声明的变量放入 AssetImage 中

android - 使用切换按钮创建可扩展的 flutter

dart - Flutter中使用ClipRRect()的一个问题

flutter - 使用 Pageview.builder 在 Flutter 中分页

dart - SingleChildScrollView 底部溢出 42 像素