将SliverList与FutureBuilder项目一起使用不会添加列表分页,Flutter

问题描述

我得到的不是错误,但是问题是当我获取下10条记录时,记录来了并在logcat中打印,但是在SliverList中记录未添加到列表中,我不知道确切是什么问题是,数据来了并且更新了列表,并且突然将其恢复为列表长度的先前状态,这意味着当我尝试使用fetchmore方法时,列表长度被更新为10至20,然后突然又恢复为10,所以请帮我解决这个问题问题。

  @override
void initState() {
super.initState();
_controller = ScrollController();
_controller.addListener(_scrollListener);
loadMyProduct();


}
  _scrollListener() {
if (_controller.offset >= _controller.position.maxScrollExtent &&
    !_controller.position.outOfRange) {

  fetchMoreProduct(listProduct.length+1);
}
if (_controller.offset <= _controller.position.minScrollExtent &&
    !_controller.position.outOfRange) {
  setState(() {
    print("at top");
  });
}


}



bool isMoreRunning=false;
  fetchMoreProduct(int newLength)async{
    //if(isMoreRunning==false && totalProducts>newLength){
      print("new length  "+newLength.toString());
        isMoreRunning=true;
    visibleMore=true;

    print(totalProducts);

  var url="http://ochapchap.com/api/productList";
  SharedPreferences prefs = await SharedPreferences.getInstance();

  String  userid=prefs.getString('userid');
  var data = {
    "startLimit":newLength.toString(),"language":"en","userId":userid};
  var response = await http.post(url,body: json.encode(data));

  if(response.statusCode==200) {
    FeedCheckProduct checkLogin =FeedCheckProduct.fromJson(json.decode(response.body));

    if(checkLogin.success==1){
      List<FeedProduct> newProduct=(jsonDecode(response.body)['result'] as List).map((i) => FeedProduct.fromJson(i)).toList();

      newProduct.forEach((element) async{
          print(element.name+" "+element.price);
          listProduct.add(element);
      });
      print("NEW PRODUCT LENGTH  "+listProduct.length.toString());
      setState(() {
        listProduct.length;
      });
        visibleMore=false;
    }
  /*}else{
    setState(() {
      isMoreRunning=false;
      isProductLoad=false;
      visibleMore=false;
    });
    Fluttertoast.showToast(
        msg: "Try after some time!.",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.CENTER,timeInSecForIosWeb: 1,backgroundColor: Colors.red,textColor: Colors.white,fontSize: 16.0
    );
  }*/
}
}

Future<List<FeedProduct>> loadProduct()async{
Future.delayed(const Duration(seconds: 3));

setState(() {
  isProductLoad=true;
});
Map<String,String> requestHeaders = {
  'Content-type': 'application/json','Accept': 'application/json',};
var url="http://ochapchap.com/api/productList";
SharedPreferences prefs = await SharedPreferences.getInstance();

String  userid=prefs.getString('userid');
String language=prefs.getString('language');
if(language==null){
  language="en";
}
var data = {
  "startLimit":"0","language": language,"userId":userid};

var response = await http.post(url,body: json.encode(data),headers: requestHeaders);
if(response.statusCode==200) {
  FeedCheckProduct checkLogin =FeedCheckProduct.fromJson(json.decode(response.body));
  setState(() {
    totalProducts=checkLogin.totalCount;
  });
  if(checkLogin.success==1){
    Map<String,dynamic> mainData=json.decode(response.body);
    listProduct=(jsonDecode(response.body)['result'] as List).map((i) => FeedProduct.fromJson(i)).toList();
    print("rrrrrrrrrrrrrrrrrrrr "+listProduct.length.toString());
    return listProduct;
  }
}else{
  setState(() {
    isProductLoad=false;
  });
}


}
 
@override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ShowProduct(),);
  }
Widget ShowProduct(){
  return Column(
    children: <Widget>[
      Expanded(
        child: FutureBuilder(
          future: loadProduct(),builder: (BuildContext context,AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return CustomScrollView(
                controller: _controller,slivers: <Widget>[
                  SliverAppBar(
                    title: Text("Home"),floating: true,),SliverList(
                    delegate: SliverChildBuilderDelegate(
                        (BuildContext context,int index){
                            return ProductList(
                              product:listProduct[index],index: index,);

                        },childCount: listProduct.length,],);
   Visibility(
        visible: visibleMore,child: Padding(
          padding: const EdgeInsets.fromLTRB(0.0,8.0,0.0,30.0),child: new CircularProgressIndicator(),)
    ],);

}

解决方法

https://stackoverflow.com/a/61392563/13608248有一个更好的答案,或者不使用FutureBuilder,因为它代表了存储库收到的数据。该过程应为:显示初始数据->调用下一个N数据->应将N个记录添加到同一列表中->父小部件应通知列表更新(即通过setState)