How to: Check if a ListView is scrollable/larger than screen

Viewed 761

I would like to determine whether a ListView is scrollable or displaying items larger than the screen.

This is because I would like a show a toast message to inform the user to scroll down but only if the ListView's children are scrollable e.g. on some larger devices the list may not actually need to scroll in order to display an image but on smaller devices a large image inside of a ListView may be scrollable.

2 Answers

You can get ListView's content height by accessing controller.position.maxScrollExtent on controller's listener.

final ScrollController controller = ScrollController();

@override
void initState() {
  _controller.addListener(_scrollListener);
 
  super.initState();
}

@override
void dispose() {
  _controller?.removeListener(_scrollListener);
  _controller.dispose();
 
  super.dispose();
}

void _scrollListener() {
  // you can access the height of ListView content using maxScrollExtent
  print(_controller.position.maxScrollExtent);

  // if you wanna get once you can directly removeListener
  // _controller.removeListener(_scrollListener);
}

You need to attach _controller to ListView's controller

Take screen size form MediaQuery.of(context).size.height first as a reference for the screen size.

Then now check this reference size with the height of the listView, and set a bool variable true or false to show the toast


Example:

double screenSize=MediaQuery.of(context).size.height

If your ListView has one tile of height 30.0 including top and bottom the margins for the tile. and there are 10 tiles. Then the ListView height would be 300.0

Now if the screen size is greater than 300.0 then there is no need to show the toast and if it is smaller then show the toast

Related