Flutter:FutureBuilder 中的异步调用
Posted
技术标签:
【中文标题】Flutter:FutureBuilder 中的异步调用【英文标题】:Flutter: Async call inside FutureBuilder 【发布时间】:2021-07-18 01:26:28 【问题描述】:我有一个异步调用,它让我得到一个objects
的列表,我从中生成一个带有ListView.builder
的ListView。每个对象都有一个名为usedId
的属性,它是一个整数。
我正在尝试基于其id
获取user object
。
这是我的 FutureBuilder:
FutureBuilder<MyObjects>(
future: getMyObjects(),
builder: (context, snapshot)
if (snapshot.hasError) return Text('Error $snapshot.error');
if (snapshot.connectionState != ConnectionState.done) return Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: snapshot.data.content.length,
itemBuilder: (BuildContext context, int index)
// Get user by its id
User user;
Future<User> futureUser = QuestionRestApi.getStatistics(snapshot.data.userId);
futureUser.then((data)
print(user);
user = data;
);
return Text('Username: user.username');
)
);
我的用户被打印在 then() 函数中,但是因为它必须等待它。我只是不知道如何处理异步调用中的异步调用。
【问题讨论】:
【参考方案1】:您需要多个 FutureBuilder:
FutureBuilder<MyObjects>(
future: getMyObjects(),
builder: (context, snapshot)
if (snapshot.hasError) return Text('Error $snapshot.error');
if (snapshot.connectionState != ConnectionState.done) return Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: snapshot.data.content.length,
itemBuilder: (BuildContext context, int index)
return FutureBuilder<User>(
future: QuestionRestApi.getStatistics(snapshot.data.userId),
builder: (context, userSnapshot)
return Text('Username: $userSnapshot.data.username');
)
);
这将为每个列表项调用QuestionRestApi.getStatistics
(因此有多个请求)
但如果您只需要检索此用户一次: Can I use multiple method on a future builder?
【讨论】:
以上是关于Flutter:FutureBuilder 中的异步调用的主要内容,如果未能解决你的问题,请参考以下文章