Flutter上拉加載下拉刷新

簡單學(xué)習(xí)記錄下,flutter的簡單的上拉加載下拉刷新

效果圖


refresh.gif

上代碼

class RefreshWidget extends StatefulWidget {

  @override
  _RefreshState createState() {
    return _RefreshState();
  }

}

class _RefreshState extends State<RefreshWidget> {
  // 用一個(gè)key來保存下拉刷新控件RefreshIndicator
  GlobalKey<RefreshIndicatorState> _refreshKey = GlobalKey<RefreshIndicatorState>();
  // 承載listView的滾動視圖
  ScrollController _scrollController = ScrollController();
  // 數(shù)據(jù)源
  List<String> _dataSource = List<String>();
  // 當(dāng)前加載的頁數(shù)
  int _pageSize = 0;

  // 加載數(shù)據(jù)
  void _loadData(int index) {
    for (int i=0; i<15; i++) {
      _dataSource.add((i+15*index).toString());

    }
  }

  // 下拉刷新
  Future<Null> _onRefresh() {
    return Future.delayed(Duration(seconds: 2), () {
      print("正在刷新...");
      _pageSize = 0;
      _dataSource.clear();
      setState(() {
        _loadData(_pageSize);
      });
    });
  }

  // 加載更多
  Future<Null> _loadMoreData() {
    return Future.delayed(Duration(seconds: 1), () {
      print("正在加載更多...");

      setState(() {
        _pageSize++;
        _loadData(_pageSize);
      });
    });
  }

  // 刷新
  showRefreshLoading() {
    new Future.delayed(const Duration(seconds: 0), () {
      _refreshKey.currentState.show().then((e) {});
      return true;
    });
  }

  @override
  void initState() {
    showRefreshLoading();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _loadMoreData();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      key: _refreshKey,
      onRefresh: _onRefresh,
      child: ListView.separated(
        controller: _scrollController,
        padding: EdgeInsets.all(8.0),
        physics: const AlwaysScrollableScrollPhysics(),
        itemBuilder: (buildContext, index) {
          return items(context, index);
        },
        itemCount: _dataSource.isEmpty ? 0 : _dataSource.length+1,
        separatorBuilder: (buildContext, index) {
          return Divider(
            height: 1,
            color: Colors.lightGreen,
          );
        },
      ),
    );
  }

  // item控件
  Widget items(context, index) {
    if (index == _dataSource.length) {
      return Container(
        child: Padding(
            padding: const EdgeInsets.all(15.0),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  CircularProgressIndicator(
                    backgroundColor: Theme.of(context).primaryColor,
                  ),
                  SizedBox(
                    width: 10.0,
                  ),
                  Text(
                    "正在加載",
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14.0,
                        color: Colors.deepPurple
                    ),
                  )
                ],
              ),
            )
        ),
      );
    }
    return Center(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Text.rich(TextSpan(
              children: [
                TextSpan(text: "我是第"),
                TextSpan(
                    text: "${_dataSource[index]}",
                    style: TextStyle(
                        color: Colors.red,
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold
                    )
                ),
                TextSpan(text: "個(gè)")
              ]
          )),
        )
    );
  }
}

這里有段代碼

// 刷新
  showRefreshLoading() {
    new Future.delayed(const Duration(seconds: 0), () {
      _refreshKey.currentState.show().then((e) {});
      return true;
    });
  }

_refreshKey.currentState.show()表示刷新時(shí)的頭部,他放在一個(gè)延時(shí)的異步操作中,當(dāng)時(shí)還在考慮為什么放在異步里,直接在initState里調(diào)用不行么,試了一下,報(bào)錯(cuò),錯(cuò)誤日志是因?yàn)?code>RefreshIndicator為空,也就是圖層還沒渲染完成,build方法還沒執(zhí)行完,這里加異步是為了等渲染完成后再進(jìn)行操作,即使延遲時(shí)間為0秒。

另外注意RefreshIndicator這個(gè)Widget,里面有一個(gè)onRefresh屬性,他只接收一個(gè)Future對象,所以為什么這里下拉刷新,加載更多方法要設(shè)置返回值為Future。

還有這里的itemCount屬性為

 _dataSource.isEmpty ? 0 : _dataSource.length+1

是當(dāng)沒有數(shù)據(jù)時(shí)只有頂部圓圈存在,當(dāng)有數(shù)據(jù)時(shí),除了每條數(shù)據(jù)占據(jù)一行以外,當(dāng)滑到最下面時(shí),有一個(gè)加載widget占據(jù)一行。

另外還有flutter_easyrefresh刷新加載這個(gè)第三方,改天試試。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容