我什么时候应该使用FutureBuilder?
我想知道何时应该使用将来的构建器。例如,如果我要发出http请求并在列表视图中显示结果,那么一旦打开视图,我是否必须使用future生成器或仅构建ListViewBuilder类似的生成器:
new ListView.builder( itemCount: _features.length,
itemBuilder: (BuildContext context, int position) {
...stuff here...
}
此外,如果我不想构建列表视图,而是想要构建一些更复杂的东西(例如圆形图表),是否应该使用Future Builder?
希望它足够清楚!
回答:
FutureBuilder 一些 。
假设您要fetch data from backend启动页面并显示加载程序,直到数据到来。
- 有两个状态变量1.
dataFromBackend2。isLoadingFlag - 在启动时,设置
isLoadingFlag = true并根据显示loader。 - 数据到达后,请根据您的数据来设置数据
backend并进行设置isLoadingFlag = false(setState显然在内部) - 我们需要有一个
if-else在widget创作。如果isLoadingFlag是true,则显示loader其他显示data。如果失败,请显示error message。
- 在
futureFuture Builder中提供异步任务 - 基于
connectionState,秀message(loading,active(streams),done) - 基于
data(snapshot.hasError)显示视图
- 不
two flags,不setState - 反应式编程(
FutureBuilder将负责更新有关数据到达的视图)
new FutureBuilder<String>( future: _fetchNetworkCall, // async work
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting: return new Text('Loading....');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Text('Result: ${snapshot.data}');
}
},
)
我只是看了一下FutureBuilder代码,以了解使用它的 影响。
- FutureBuilder只是
StatefulWidget其state变量为_snapshot - 初始状态为
_snapshot = new AsyncSnapshot<T>.withData(ConnectionState.none, widget.initialData); - 订阅
future我们要发送的构造函数并state基于该更新。
widget.future.then<void>((T data) { if (_activeCallbackIdentity == callbackIdentity) {
setState(() {
_snapshot = new AsyncSnapshot<T>.withData(ConnectionState.done, data);
});
}
}, onError: (Object error) {
if (_activeCallbackIdentity == callbackIdentity) {
setState(() {
_snapshot = new AsyncSnapshot<T>.withError(ConnectionState.done, error);
});
}
});
因此,这FutureBuilder是我们通常所做的工作的包装/样板。因此,不应有任何性能影响。
以上是 我什么时候应该使用FutureBuilder? 的全部内容, 来源链接: utcz.com/qa/404485.html


