Solian/lib/screens/explore.dart

82 lines
2.5 KiB
Dart
Raw Normal View History

2024-04-13 11:47:31 +00:00
import 'dart:convert';
2024-04-12 16:38:20 +00:00
import 'package:flutter/material.dart';
2024-04-13 11:47:31 +00:00
import 'package:solian/models/pagination.dart';
import 'package:solian/models/post.dart';
import 'package:solian/utils/service_url.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
2024-04-12 16:38:20 +00:00
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
2024-04-13 11:47:31 +00:00
import 'package:http/http.dart' as http;
import 'package:solian/widgets/posts/item.dart';
import 'package:solian/widgets/wrapper.dart';
2024-04-12 16:38:20 +00:00
class ExploreScreen extends StatefulWidget {
const ExploreScreen({super.key});
@override
State<ExploreScreen> createState() => _ExploreScreenState();
}
class _ExploreScreenState extends State<ExploreScreen> {
2024-04-13 11:47:31 +00:00
final PagingController<int, Post> _pagingController =
PagingController(firstPageKey: 0);
final http.Client _client = http.Client();
Future<void> fetchFeed(int pageKey) async {
final offset = pageKey;
const take = 5;
var uri =
getRequestUri('interactive', '/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 items =
result.data?.map((x) => Post.fromJson(x)).toList() ?? List.empty();
final isLastPage = (result.count - pageKey) < take;
if (isLastPage || result.data == null) {
_pagingController.appendLastPage(items);
} else {
final nextPageKey = pageKey + items.length;
_pagingController.appendPage(items, nextPageKey);
}
} else {
_pagingController.error = utf8.decode(res.bodyBytes);
}
}
2024-04-12 16:38:20 +00:00
@override
void initState() {
super.initState();
2024-04-13 11:47:31 +00:00
_pagingController.addPageRequestListener((pageKey) => fetchFeed(pageKey));
2024-04-12 16:38:20 +00:00
}
@override
Widget build(BuildContext context) {
return LayoutWrapper(
title: AppLocalizations.of(context)!.explore,
child: RefreshIndicator(
onRefresh: () => Future.sync(
() => _pagingController.refresh(),
),
child: Center(
child: Container(
constraints: const BoxConstraints(maxWidth: 720),
child: PagedListView<int, Post>.separated(
pagingController: _pagingController,
separatorBuilder: (context, index) => const Divider(thickness: 0.3),
builderDelegate: PagedChildBuilderDelegate<Post>(
itemBuilder: (context, item, index) => PostItem(item: item),
),
2024-04-13 11:47:31 +00:00
),
),
),
),
2024-04-12 16:38:20 +00:00
);
}
}