flutter-实现一个下拉刷新上拉加载的列表

1.下拉刷新:s使用自带的控件实现

new RefreshIndicator(
        onRefresh: onRefresh,
        child: ListView.builder(
          physics: new AlwaysScrollableScrollPhysics(),
          itemBuilder: getItemView,
          itemCount: isShowLoadmore ? datas.length + 1 : datas.length,
          controller: scrollController,
        ),
      ),

 

2.上拉加载:监听listview滚动到底部的时间,如果滚动到底部,设置listview的长度是length+1,在获取子view的方法中,处理加载中显示的view。

给listview添加滚动到底部的监听器

 ScrollController scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //对上拉加载更多的处理
    scrollController.addListener(() {
      if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent - 10) {
        if (!isShowLoadmore) {
          //滚动到底部
          setState(() {
            isShowLoadmore = true;
            getDataByIndex(index + 1);
          });
        }
      }
    });

    getDataByIndex(0);
  }

2.对listview的getItemview进行处理

 //渲染子view
  Widget getItemView(BuildContext context, int positon) {
    if (positon >= datas.length) {
      if (isShowLoadmore) {
        return new Container(
          height: 50,
          child: new Center(
            child: new Text("下拉加载更多..."),
          ),
        );
      }
      return null;
    }
    return new GestureDetector(
      child: new Container(
        decoration: new BoxDecoration(
            border: Border.all(color: Colors.greenAccent, width: 2)),
        padding: EdgeInsets.only(left: 10, top: 20, bottom: 20),
        child: new Text(datas[positon]),
      ),
    );
  }

3.加载数据和onfresh的处理

Future getDataByIndex(needLoadIndex) async {
    if (isLoading) {
      setState(() {
        isLoading = false;
        isShowLoadmore = false;
      });
      return;
    }
    setState(() {
      isLoading = true;
    });

    await Future.delayed(Duration(seconds: 4), () {
      setState(() {
        index = needLoadIndex;
        for (int i = 0; i < 10; i++) {
          datas.add("第" + index.toString() + "页第" + i.toString() + "条数据");
        }
        isLoading = false;
        isShowLoadmore = false;
        datas = datas;
      });
    });
  }

 

Future onRefresh() async {
    if (isLoading) {
      setState(() {
        isLoading = false;
        isShowLoadmore = false;
      });
      return;
    }
    await Future.delayed(Duration(seconds: 3), () {
      setState(() {
        index = 0;
        isLoading = false;
        if (index == 0) {
          datas.clear();
        }
        for (int i = 0; i < 10; i++) {
          datas.add("第" + index.toString() + "页第" + i.toString() + "条数据");
        }
        datas = datas;
      });
    });
  }

 

你可能感兴趣的:(Flutter)