Flutter getx无限滚动刷新listview每结束滚动

问题描述 投票:0回答:2

我正在尝试在列表视图中进行无限滚动。我正在从 API 获取数据。我正在使用 getx。我的列表视图总是在滚动结束时重建。我找不到我哪里做错了。

这就是我尝试做的

我的模特班;

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())));

我的控制器;

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);
    }
  }
}

我的API调用;

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;
    }

我的视图(StatefulWidget);

最终 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,
      }
...
flutter infinite-scroll flutter-getx
2个回答
1
投票

我认为这应该可以解决你的问题。

itemCount: exploreController.articleList.length + 1 
并在 itemBuilder 中添加条件
if (index == exploreController.articleList.length) //show progress indicator or somthing else
或者 你可以这样做 将您的列更改为列表视图并这样做

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() )

]


0
投票

我用

NotificationListener<ScrollNotification>
实现了无限滚动,因为
ScrollController
条件太麻烦了。它的工作原理如下:

NotificationListener<ScrollNotification>(
  onNotification: (scrollNotification) {
  if (scrollNotification is ScrollEndNotification) {
    onScrollListener();
  }

  return true;
}

void onScrollListener() {
  if (reachedEnd) {
    return;
  }

  if (!isPageLoading) {
    isPageLoading = true;
    Future.microtask(() async {
      final newItems = await getItemsUseCase.get(page: nextPage);
      if (newItems.length < pageSize) {
        reachedEnd= true;
      } else {
        nextPage++;
      }

      allItems.addAll(newItems);
      isPageLoading = false;
    });
  }
}

我在这里添加了完整的代码示例

© www.soinside.com 2019 - 2024. All rights reserved.