Flutter中ScrollView及其子类(ListView等)的下拉刷新

时间:2022-06-09
本文章向大家介绍Flutter中ScrollView及其子类(ListView等)的下拉刷新,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

先丢一个github的demo代码地址 移动开发发展到现在,下拉刷新是个必不可少的功能了。

Flutter里面的ScrollView及其子view都可以添加下拉刷新功能,只要在view的上层再包裹一层RefreshIndicator,这个下拉刷新是MD风格的。

几个要注意的点(以ListView为例)

  • 如果ListView的内容不足一屏,要设置ListView的physics属性为const AlwaysScrollableScrollPhysics()
  • onRefresh方法是接受一个Future<Null>的参数
  • 通过代码触发下拉 _refreshIndicatorKey.currentState.show();

声明一个key来保存控件

final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = new GlobalKey<
      RefreshIndicatorState>();
body: new RefreshIndicator(
        key: _refreshIndicatorKey,
        onRefresh: _getData, // onRefresh 参数是一个 Future<Null> 的回调
        child: new ListView.builder(
          // 这句是在list里面的内容不足一屏时,list可能会滑不动,加上就一直都可以滑动
          physics: const AlwaysScrollableScrollPhysics(),
          itemCount: this.list.length,
          itemBuilder: (_, int index) => _createItem(list[index]),
        ),
      ),
Future<Null> _getData() {
    final Completer<Null> completer = new Completer<Null>();

    // 启动一下 [Timer] 在3秒后,在list里面添加一条数据,关完成这个刷新
    new Timer(Duration(seconds: 3), () {
      // 添加数据,更新界面
      setState(() {
        list.add("新加数据${list.length}");
      });

      // 完成刷新
      completer.complete(null);
    });

    return completer.future;
  }

关于学习

flutter的学习文章都整理在这个github仓库