gpt4 book ai didi

Flutter getx 无限滚动每次结束滚动刷新 ListView

转载 作者:行者123 更新时间:2023-12-04 17:19:51 29 4
gpt4 key购买 nike

我正在尝试在 ListView 中无限滚动。我正在从 API 获取数据。我正在使用 getx。我的 ListView 总是在滚动结束时重建。我找不到我做错的地方。
This is what i try to make
我的模型课;

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())));
我的 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);
}
}
}
我的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 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,
}
...

最佳答案

我认为这应该可以解决您的问题。itemCount: exploreController.articleList.length + 1 并在 itemBuilder 添加条件 if (index == exploreController.articleList.length) //show progress indicator or somthing else或者
你可以这样做
将您的列更改为 ListView 并这样做

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

关于Flutter getx 无限滚动每次结束滚动刷新 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66879040/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com