我正在尝试在列表视图中进行无限滚动。我正在从 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);
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,
}
...