Flutter嵌套ListView使用ScrollController监听滚动到底部无响应如何解决
问题根因
你的代码不生效的核心原因是:
- 内层
ListView.builder配置了shrinkWrap: true,它的高度会自动适配所有子项的总高度,本身不会产生独立的滚动行为,滚动事件完全由外层ListView接管,所以绑定在内层的ScrollController根本接收不到滚动回调。
解决方案1:期望整个页面统一滚动(大部分嵌套列表的常规需求)
把ScrollController绑定到外层的ListView上即可,同时可以把判断条件放宽一点,避免滚动回弹导致的判定失败:
class _CategoryScreenState extends State<CategoryScreen> { // 滚动控制器绑定给外层ListView ScrollController scrollController = ScrollController(); @override void initState() { super.initState(); scrollController.addListener(() { // 放宽判定阈值,避免回弹等场景漏触发 if(scrollController.position.pixels >= scrollController.position.maxScrollExtent - 10){ if(!scrollController.position.outOfRange) { // 排除超出滚动范围的越界情况 print('At the end'); } } }); } @override void dispose() { scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( key: widget._scaffoldKey, body: SafeArea( // 滚动控制器绑到外层ListView child: ListView( controller: scrollController, children: <Widget>[ Stack(....), const SizedBox(height: 10), ListView.builder( key: UniqueKey(), itemCount: myProvider.myArray.length, shrinkWrap: true, // 内层不需要controller,同时禁用内层滚动行为 physics: const NeverScrollableScrollPhysics(), itemBuilder: (_,index){ return MyWidget( dishModel: myProvider.myArray[index], ); } ), ], ) ), ); } }
解决方案2:期望内层列表独立滚动
如果你的需求是外层的Stack等固定,只有下方的列表区域可以滚动,那就需要给内层列表固定高度,禁用shrinkWrap,同时配置独立滚动属性:
核心修改代码片段:
ListView( physics: const NeverScrollableScrollPhysics(), // 外层禁用滚动 children: <Widget>[ Stack(....), const SizedBox(height: 10), // 给内层列表套固定高度的容器 SizedBox( height: MediaQuery.of(context).size.height - 200, // 自定义高度,减掉上层控件的总高度 child: ListView.builder( key: UniqueKey(), itemCount: myProvider.myArray.length, controller: scrollController, // 移除shrinkWrap: true配置 physics: const AlwaysScrollableScrollPhysics(), itemBuilder: (_,index){ return MyWidget( dishModel: myProvider.myArray[index], ); } ), ) ], )
补充优化建议:两层ListView嵌套的实现性能较差,如果是页面整体滚动的场景,更推荐使用
CustomScrollView+ Sliver系列组件实现,渲染效率更高。
内容的提问来源于stack exchange,提问作者GTF
相关产品推荐
相关产品推荐

