import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import 'package:solaragent/models/feed.dart'; import 'package:solaragent/models/pagination.dart'; import 'package:http/http.dart' as http; import 'package:solaragent/widgets/feed.dart'; class ExploreScreen extends StatefulWidget { const ExploreScreen({super.key}); @override State createState() => _ExploreScreenState(); } class _ExploreScreenState extends State { static const pageSize = 5; final client = http.Client(); final PagingController paginationController = PagingController(firstPageKey: 0); List feed = List.empty(); @override void initState() { super.initState(); paginationController.addPageRequestListener((pageKey) { pullFeed(pageKey); }); } Future pullFeed(int pageKey) async { var offset = pageKey; var take = pageSize; var uri = Uri.parse('https://co.solsynth.dev/api/feed?take=$take&offset=$offset'); var res = await client.get(uri); if (res.statusCode == 200) { final result = PaginationResult.fromJson(jsonDecode(utf8.decode(res.bodyBytes))); final isLastPage = (result.data?.length ?? 0) < pageSize; if (isLastPage) { paginationController.appendLastPage(feed); } else { final feed = result.data!.map((x) => Feed.fromJson(x)).toList(); final nextPageKey = pageKey + feed.length; paginationController.appendPage(feed, nextPageKey); } } else { paginationController.error = utf8.decode(res.bodyBytes); } } @override Widget build(BuildContext context) { return Scaffold( body: PagedListView( pagingController: paginationController, builderDelegate: PagedChildBuilderDelegate( itemBuilder: (context, item, index) => FeedItem( item: item, ), ), ), ); } @override void dispose() { paginationController.dispose(); super.dispose(); } }