I want to make a pagination to my application using hacker news api, I want load more data when I scroll down and add new items to old items I have in the first page.
That's the code of the item page, I use a bloc pattern I wend variable named size to the bloc withe the event ant in the bloc I fetch only 6 items in the first load and when I scroll down I add 6 item to my loop ...
class _TopPageState extends State<TopPage> {
@override
void initState() {
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
size = size + 6;
context.read<ItemBloc>().add(GetTopEvent(size));
}
});
super.initState();
}
@override
void dispose() {
super.dispose();
_scrollController.dispose();
}
ScrollController _scrollController = new ScrollController();
int size = 6;
bool isLoading = false;`enter code here`
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: BlocBuilder<ItemBloc, ItemState>(
builder: (context, state) {
if (state.topState == RequestState.LOADING) {
return const CircularProgressIndicator();
} else if (state.topState == RequestState.ERROR) {
print(state.errorMsg);
return Container();
}else if (state.topState == RequestState.NONE) {
context.read<ItemBloc>().add(GetTopEvent(size));
return Container();
}
else if (state.topState == RequestState.LOADED) {
return NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
_getMoreData(notification.metrics);
}
return true;
},
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.symmetric(vertical: 8.0),
itemCount: state.reposTop.length,
itemBuilder: (context, index) {
return GestureDetector(
child: Item(state.reposTop[index]),
onTap: () {
if (state.reposTop[index].url != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
WebViewPage(state.reposTop[index])),
);
} else if (state.reposTop[index].text != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ItemDetails(state.reposTop[index])),
);
}
});
}),
);
} else {
return Container();
}
},
),
),
);
}
void _getMoreData(ScrollMetrics metrics) {
if (_scrollController.position.pixels ==
_scrollController.position.minScrollExtent) {
//&& size != 5
if( size - 6 <=0){
context.read<ItemBloc>().add(GetTopEvent(size));
}
else{
size = size - 6;
}
context.read<ItemBloc>().add(GetTopEvent(size));
}
}
}