Flutter ListView 延迟加载 [英] Flutter ListView lazy loading

查看:31
本文介绍了Flutter ListView 延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现无限列表视图的项目延迟加载?当用户滚动到列表视图的末尾时,我想通过网络加载更多项目.

How can I realize items lazy loading for endless listview? I want to load more items by network when user scroll to the end of listview.

推荐答案

你可以听一个 ScrollController.

You can listen to a ScrollController.

ScrollController 有一些有用的信息,例如 scrolloffset 和 ScrollPosition.

ScrollController has some useful information, such as the scrolloffset and a list of ScrollPosition.

在你的例子中,有趣的部分在 controller.position 中,它是当前可见的 ScrollPosition.表示可滚动的一段.

In your case the interesting part is in controller.position which is the currently visible ScrollPosition. Which represents a segment of the scrollable.

ScrollPosition 包含有关它在可滚动内容中的位置的信息.如extentBeforeextentAfter.或者它的大小,带有 extentInside.

ScrollPosition contains informations about it's position inside the scrollable. Such as extentBefore and extentAfter. Or it's size, with extentInside.

考虑到这一点,您可以根据表示剩余可用滚动空间的 extentAfter 触发服务器调用.

Considering this, you could trigger a server call based on extentAfter which represents the remaining scroll space available.

这是一个使用我所说内容的基本示例.

Here's an basic example using what I said.

class MyHome extends StatefulWidget {
  @override
  _MyHomeState createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  ScrollController controller;
  List<String> items = List.generate(100, (index) => 'Hello $index');

  @override
  void initState() {
    super.initState();
    controller = ScrollController()..addListener(_scrollListener);
  }

  @override
  void dispose() {
    controller.removeListener(_scrollListener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Scrollbar(
        child: ListView.builder(
          controller: controller,
          itemBuilder: (context, index) {
            return Text(items[index]);
          },
          itemCount: items.length,
        ),
      ),
    );
  }

  void _scrollListener() {
    print(controller.position.extentAfter);
    if (controller.position.extentAfter < 500) {
      setState(() {
        items.addAll(List.generate(42, (index) => 'Inserted $index'));
      });
    }
  }
}


你可以清楚地看到,当到达滚动的末尾时,由于加载了更多的项目,滚动条会消耗掉.


You can clearly see that when reaching the end of the scroll, it scrollbar expends due to having loaded more items.

这篇关于Flutter ListView 延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆