我正在创建一个包含项目列表的页面。列表呈现后,我想滚动到页面底部。问题是我正在使用FutureBuilder来获取列表。如果我使用WidgetsBinding.addPostFrameCallback
,这似乎会在build()
方法完成之前被调用(也许是因为它仍在获取数据的过程中)。
是否有办法弄清楚Future是否已完成,列表已呈现,然后才触发滚动到底部?
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) => _postInit());
super.initState();
}
Future<void> _postInit() async {
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _getList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch(snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: SizedBox(height: 100, width: 100, child: new CircularProgressIndicator()));
break;
default:
if(snapshot.hasError) {
return Container();
} else {
return _buildListView(snapshot.data);
}
}
}
)
);
}
Widget _buildListView(list) {
return Column(
children: <Widget>[
Expanded(
child: ListView(
controller: _scrollController,
shrinkWrap: true,
children: list,
),
),
],
);
}
答案 0 :(得分:1)
尝试从您的WidgetsBinding.instance.addPostFrameCallback((_) => _postInit());
方法中删除initState
。
然后,在delayed
方法内添加一个_postInit()
函数,并在收到数据以显示列表时调用它,如下所示:
Future<void> _postInit() async {
await Future.delayed(Duration(milliseconds: 100));
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _getList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch(snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: SizedBox(height: 100, width: 100, child: new CircularProgressIndicator()));
break;
default:
if(snapshot.hasError) {
return Container();
} else {
_postInit();
return _buildListView(snapshot.data);
}
}
}
)
);
}