我有一个使用 TabBar 的小部件。父小部件进行 http 调用,该调用需要在 TabBar 小部件被绘制之前完成(它们使用数据)。我如何强制 TabBarView 小部件等待父 http 调用完成并让我设置状态变量,然后在 TabBarView 小部件中使用该变量。似乎解决方案是对所有 TabBar 小部件使用 FutureBuilder,但是这些小部件如何知道等待父级完成?这些小部件等待父级的数据。
父小部件 - 进行 http 调用,设置状态变量 x TabBarView 小部件,等待 x。抛出错误是因为在设置 x 之前调用了 TB1,除非我输入一些虚拟数据。
父小部件
void initState() {
x = await _getdata();
setState(() => this.x = x);
}
...
TabBarView(
controller: _tabController,
children: [
new TB1(x),
new TB2(x),
new TB3(x),
]
)
您可以有条件地构建您的小部件
DataType x = null;
void initState() {
_getdata().then((_x) {
if (mounted){ // Just to be sure is safe to call setState, since _getdata is asynchronous
setState(() => x = _x);
}
});
}
Widget build(BuildContext context){
// Loading
if (x == null){
return CircularProgressIndicator();
}else{
return TabBarView(...);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句