import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import 'package:solaragent/auth.dart'; import 'package:solaragent/models/feed.dart'; import 'package:solaragent/models/pagination.dart'; import 'package:solaragent/router.dart'; import 'package:solaragent/widgets/feed.dart'; class CommentListWidget extends StatefulWidget { final Feed parent; const CommentListWidget({super.key, required this.parent}); @override State createState() => _CommentListWidgetState(); } class _CommentListWidgetState extends State { static const pageSize = 5; final client = 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 dataset = "${widget.parent.modelType}s"; var alias = widget.parent.alias; var uri = Uri.parse( 'https://co.solsynth.dev/api/p/$dataset/$alias/comments?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.count - pageKey) < pageSize; final items = result.data?.map((x) => Feed.fromJson(x)).toList() ?? List.empty(); if (isLastPage || result.data == null) { paginationController.appendLastPage(items); } else { final nextPageKey = pageKey + items.length; paginationController.appendPage(items, nextPageKey); } } else { paginationController.error = utf8.decode(res.bodyBytes); } } @override Widget build(BuildContext context) { return Column( children: [ Container( padding: const EdgeInsets.only(left: 10, right: 10, top: 20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.symmetric( horizontal: 8.0, vertical: 12.0, ), child: Text( 'Comments', style: Theme.of(context).textTheme.headlineSmall, ), ), FutureBuilder( future: authClient.isAuthorized(), builder: (context, snapshot) { if (snapshot.hasData && snapshot.data == true) { return TextButton.icon( icon: const Icon(Icons.edit), label: const Text("LEAVE COMMENT"), onPressed: () { router .push("/post/comments", extra: widget.parent) .then((value) { if (value == true) paginationController.refresh(); }); }, ); } else { return Container(); } }, ), ], ), ), Expanded( child: PagedListView( pagingController: paginationController, builderDelegate: PagedChildBuilderDelegate( itemBuilder: (context, item, index) => FeedItem( item: item, ), ), ), ), ], ); } @override void dispose() { paginationController.dispose(); super.dispose(); } }