可以,可以使用ListView的onScrollEndDragged属性来监听用户滑动到底部的事件,然后在回调函数中触发加载更多数据的方法。具体实现可以参考下面的代码:

class _homeState extends State<home> {
  var _productList = [];
  int _currentPage = 1;
  int _pageSize = 20;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _getProducts();
  }

  void _getProducts() async {
    setState(() {
      _isLoading = true;
    });
    List productList = await GetProduct.getProducts(_currentPage, _pageSize);
    setState(() {
      _productList.addAll(productList);
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('商品列表'),
      ),
      body: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification notification) {
          if (!_isLoading &&
              notification.metrics.pixels == notification.metrics.maxScrollExtent) {
            _currentPage++;
            _getProducts();
            return true;
          }
          return false;
        },
        child: ListView.builder(
          itemCount: _productList.length + 1,
          itemBuilder: (BuildContext context, int index) {
            if (index == _productList.length) {
              return _isLoading ? CircularProgressIndicator() : SizedBox.shrink();
            }
            product products = _productList[index];
            return ProductCard(
              imageUrl: products.imageUrl,
              title: products.name,
              price: products.price.toString(),
            );
          },
        ),
      ),
    );
  }
}

在这个实现中,我们在ListView的外面包了一个NotificationListener来监听滑动事件。当用户滑动到底部时,onNotification回调函数会被触发,我们在这里判断如果没有正在加载数据,就增加当前页数并调用_getProducts方法来获取更多数据。同时,在ListView的itemBuilder中,我们对最后一个item进行特殊处理,如果正在加载数据,就显示一个CircularProgressIndicator,否则就返回一个SizedBox.shrink()来隐藏这个item。

Flutter ListView 实现拉到底自动加载更多数据

原文地址: https://www.cveoy.top/t/topic/nJpe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录