Search code examples
flutterflutter-layout

How to know if list view is scrollable programatically


I am copying my question from here as it is the same question but for flutter

How do you know if your ListView has enough number of items so that it can scroll?

For instance, If I have 5 items on my ListView all of it will be displayed on a single screen. But if I have 7 or more, my ListView begins to scroll. How do I know if my List can scroll programmatically?

Thank you

I am adding the code I tried, in which I test if the controller is attached, to be able to get the position. I couldn't get the position because the controller is not attached until you actually scroll

Widget build(BuildContext context) {
  _afterBuild();
  ListView.builder(
    controller: controller,
    // ...
  )    
}

Future<void> _afterBuild () async {
    if (controller.hasClients) {
      print("controller.hasClients");
      // here I would be able to get the position
    } else {
      print("controller.has no Clients");
    }       
  }

Edit: For anyone coming here: The controller was not being attached because I had a condition under which to build the ListView

So I combined the comments with the accepted answer (which is actually the answer for the question) and solved it like this (with some pseudocode):

Widget build(BuildContext context) {
  if (not loaded results from api) {
    return Something()
  } else {
    Future(_afterBuild);
    return ListView.builder(
      controller: controller,
      // ...
    )
  }          
}

Future<void> _afterBuild () async {   
  if (controller.hasClients) {   
    if(controller.position.maxScrollExtent > 0){
      print('it can be scrolled');
    }
  } else {
    print("controller has no client");
  }            
}

Solution

  • You should have a ScrollController attached to your ListView and then you can check the maxScrollExtent. If it's bigger than zero then your ListView can be scrolled. It also works for any scrolling view which uses ScrollController.

    @override
    void initState() {
      super.initState();
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        if(controller.position.maxScrollExtent > 0){
          print('it can be scrolled');
        }
      });
    }