Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

Flutter check ability to scroll

Suppose I have a ScrollController _scrollController; Is there a way to check ability to scroll during build function?

I tried somthing like this:

  Widget build(BuildContext context) {
   final hasScroll = MediaQuery.of(context).size.height < scrollController.position.maxScrollExtent;

But as I understand it does't work because _scrollController does't attach during build() function.

Upvotes: 3

Views: 505

Answers (1)

CopsOnRoad
CopsOnRoad

Reputation: 267474

Yes, you can't use ScrollController until it is attached to the ListView. You need to use WidgetsBindingObserver's SchedulerBinding's addPostFrameCallback method. Here is the simple example demonstrating that.

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    SchedulerBinding.instance.addPostFrameCallback((duration) {
      // prints true if scrollable else false
      print("isScrollable = ${_scrollController.position.maxScrollExtent != 0}"); 
    });
  }

  Widget build() {
    return ListView.builder(
      controller: _scrollController,
      ...
  }
} 

Upvotes: 4

Related Questions