flutter

Load on scroll

Trigger some event (e.g. loading) on list scroll end

final _scrollController = ScrollController();

@override
  void initState() {
  super.initState();
  _scrollController.addListener(_onScroll);
}

void _onScroll() {
  // call load/fetch method when it reaches the bottom of a list 
  if (_isBottom) context.read<PostBloc>().add(PostFetched());
}

bool get _isBottom {
  if (!_scrollController.hasClients) return false;
  final maxScroll = _scrollController.position.maxScrollExtent;
  final currentScroll = _scrollController.offset;
  return currentScroll >= (maxScroll * 0.9);
}

//don't forget to dispose it
@override
void dispose() {
  _scrollController
  ..removeListener(_onScroll)
  ..dispose();
  super.dispose();
}
Was this helpful?