4

I am trying to make infinite scroll in listview. I am fetching data from API. I am using getx. My listview always rebuild when scroll end. I could not find where i did mistake.

This is what i try to make

My model class;

List<ExploreModel> exploreModelFromJson(String str) => List<ExploreModel>.from(
    json.decode(str).map((x) => ExploreModel.fromJson(x)).toList());

String exploreModelToJson(List<ExploreModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

My controller;

class ExploreController extends GetxController {
  var isLoading = true.obs;
  var articleList = <ExploreModel>[].obs;
  var offsetCount = 0;

  @override
  void onInit() {
    fetchArticles();
    super.onInit();
  }

  void fetchArticles({int offsetCount = 0}) async {
    try {
      isLoading(true);
      var articles = await ApiService.fetchArticleList(offsetCount);

      if (articles != null) {
        articleList.addAll(articles);
      }
    } finally {
      isLoading(false);
    }
  }
}

My api call;

static Future<List<ExploreModel>> fetchArticleList(int offsetCount) async {
    var url = Uri.http(Config().baseUrl, Config().baseUrlPathGetArticles,
        {'offsetCount': '$offsetCount'});
    var response = await http.get(url);
    if (response.statusCode == 200) {
      return exploreModelFromJson(utf8.decode(response.bodyBytes));
    } else {
      return null;
    }

My view (StatefulWidget);

final ScrollController scrollController = new ScrollController(); int offsetCount = 0;

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        offsetCount= offsetCount + 5;
        exploreController.fetchArticles(offsetCount: offsetCount);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: RefreshIndicator(
          key: _refreshIndicatorKey,
          onRefresh: () async {
            exploreController.fetchArticles();
          },
          child: Column(
            children: <Widget>[
              Expanded(
                child: Obx(() {
                  if (exploreController.isLoading.value) {
                    return CupertinoActivityIndicator();
                  }
                  return ListView.separated(
                    controller: scrollController,
                    itemCount: exploreController.articleList.length,
      }
...
jancooth
  • 555
  • 1
  • 10
  • 25
  • I think you should change your listener condition to scrollController.position.offset >= scrollController.position.maxScrollExtent – Z-Soroush Mar 30 '21 at 22:20
  • 1
    You asked a question earlier today and got an answer here https://stackoverflow.com/a/66865671/13558035 but you didn't mark it as answered there or give any updates, yet you are using the code from that answer, and added `.toList()` to your code, apparently it's working. – Huthaifa Muayyad Mar 30 '21 at 22:33
  • @HuthaifaMuayyad thanks for your reply but this code works good but when i reached at end of scroll, listview refrefshing.. I do not want this. I want this continue with new datas. – jancooth Mar 31 '21 at 06:20

1 Answers1

1

I think this should fix your problem.

itemCount: exploreController.articleList.length + 1 and in the itemBuilder add a condition if (index == exploreController.articleList.length) //show progress indicator or somthing else Or you can do this way Change your column to list view and do it this way

ListView(
        children: <Widget>[
            Obx(() {
              return ListView.separated(
                physics:NeverScrollableScrollPhysics(),
                controller: scrollController,
                itemCount: exploreController.articleList.length,
                itemBuilder(context,index){
                //show your widget
               }
  })
  Obx(()=>exploreController.isLoading.value? 
  Container(height: 100, child: CupertinoActivityIndicator())
  : Container() )

]

Z-Soroush
  • 334
  • 1
  • 3
  • 10