Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current scroll offset inside a Flutter ListView, SliverList,etc

How do I get the current scroll offset inside a Flutter ListView, GridView, SliverList`, etc?

like image 772
Eric Seidel Avatar asked May 09 '17 22:05

Eric Seidel


2 Answers

  • If you're inside the scroll view use Scrollable.of(context).position.pixels.
  • If you're outside, you probably want to hand a ScrollController in as the controller argument of the scroll view, then you can read controller.offset.
  • Alternatively, use scroll notifications with NotificationListener.

This was asked on Flutter Gitter, and answered: https://gitter.im/flutter/flutter?at=591243f18a05641b1167be0e

like image 146
Eric Seidel Avatar answered Sep 20 '22 23:09

Eric Seidel


For someone else, looking for code implementation, you can use ScrollController like this:

  • Using NotificationListener:

    NotificationListener<ScrollNotification>(
      onNotification: (scrollNotification) {
        print(scrollNotification.metrics.pixels); // <-- This is it.
        return false;
      },
      child: ListView.builder(
        itemCount: 200,
        itemBuilder: (c, i) => Text('Item $i'),
      ),
    )
    
  • Using ScrollController.offset

    final ScrollController _controller = ScrollController();
    
    @override
    void initState() {
      super.initState();
      _controller.addListener(() {
        print(_controller.offset); // <-- This is it.
      });
    }
    
    @override
    void dispose() {
      _controller.dispose();
      super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: ListView.builder(
          controller: _controller,
          itemCount: 200,
          itemBuilder: (c, i) => Text('Item $i'),
        ),
      );
    }
    
like image 44
CopsOnRoad Avatar answered Sep 20 '22 23:09

CopsOnRoad