gpt4 book ai didi

flutter - 滚动 future 的 ListView

转载 作者:IT王子 更新时间:2023-10-29 07:18:36 25 4
gpt4 key购买 nike

我正在创建一个包含项目列表的页面。我想在列表呈现后滚动到页面底部。问题是我正在使用 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,
),
),
],
);
}

最佳答案

尝试从 initState 方法中删除 WidgetsBinding.instance.addPostFrameCallback((_) => _postInit());

之后,在您的_postInit() 方法中添加一个delayed 函数,并在您收到数据时调用它来显示您的List,如下所示:

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);
}
}
}

)
);
}

关于flutter - 滚动 future 的 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com