How to detect scroll position of ListView in Flutter

You can also achieve this functionality with the following steps

import 'package:flutter/material.dart';

class YourPage extends StatefulWidget {
  YourPage({Key key}) : super(key: key);

  @override
 _YourPageState createState() => _YourPageState();
}

class _YourPageState extends State<YourPage> {

  ScrollController _scrollController;
  double _scrollPosition;

 _scrollListener() {
  setState(() {
   _scrollPosition = _scrollController.position.pixels;
 });
}

@override
void initState() {
  _scrollController = ScrollController();
  _scrollController.addListener(_scrollListener);
  super.initState();
}

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    automaticallyImplyLeading: false,
    title: Text('Position $_scrollPosition pixels'),
  ),
  body: Container(
      child: ListView.builder(
    controller: _scrollController,
    itemCount: 200,
    itemBuilder: (context, index) {
      return ListTile(
        leading: Icon(Icons.mood),
        title: Text('Item: $index'),
      );
    },
  )),
);
}
}

enter image description here


I used NotificationListener that is a widget that listens for notifications bubbling up the tree. Then use ScrollEndNotification, which indicates that scrolling has stopped.

For scroll position I used _scrollController that type is ScrollController.

NotificationListener(
  child: ListView(
    controller: _scrollController,
    children: ...
  ),
  onNotification: (t) {
    if (t is ScrollEndNotification) {
      print(_scrollController.position.pixels);
    }
    //How many pixels scrolled from pervious frame
    print(t.scrollDelta);

    //List scroll position
    print(t.metrics.pixels);
  },
),

The NotificationListener now accepts a type argument which makes the code shorter :)

NotificationListener<ScrollEndNotification>(
  child: ListView(
    controller: _scrollController,
    children: ...
  ),
  onNotification: (notification) {
    print(_scrollController.position.pixels);
    // Return true to cancel the notification bubbling. Return false (or null) to
    // allow the notification to continue to be dispatched to further ancestors.
    return true;
  },
),

majidfathi69's answer is good, but you don't need to add a controller to the list: (Change ScrollUpdateNotification to ScrollEndNotification when you only want to be notified when scroll ends.)

NotificationListener<ScrollUpdateNotification>(
  child: ListView(
    children: ...
  ),
  onNotification: (notification) {
    //How many pixels scrolled from pervious frame
    print(notification.scrollDelta);

    //List scroll position
    print(notification.metrics.pixels);
  },
),