Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for overscroll in PageView - Flutter

Tags:

flutter

dart

Hi I am using PageView in my flutter app. I want to detect when the user overscrolls and is out of pages. How do i achieve it

The code of my PageView:

PageView(
      controller: _controller,
      children: widget.imagePaths,
    ),
like image 873
Joshua Avatar asked Nov 16 '25 07:11

Joshua


2 Answers

Wrap your PageView inside a NotificationListener<OverscrollIndicatorNotification> like this. Then whenever the user overscrolls in either direction, the function onNotification is called.

return NotificationListener<
                          OverscrollIndicatorNotification>(
                        onNotification: (overscroll) {
                          print("overscrolled"); //do whatever you need to do when overscroll
                        },
                        child: PageView(
                          controller: _controller,
                          children: widget.imagePaths,
                        ),
                      );

Full script file

import 'package:flutter/material.dart';

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  Widget build(BuildContext context) {
    return NotificationListener<OverscrollIndicatorNotification>(
      onNotification: (overscroll) {
        print("overscrolled");
      },
      child: PageView(
        children: [
          Container(color: Colors.red),
          Container(color: Colors.green)
        ],
      ),
    );
  }
}
like image 50
RukshanJS Avatar answered Nov 17 '25 21:11

RukshanJS


Another solution would be to use NotificationListener<OverscrollNotification> because then you can choose to which amount of over-scroll you want to react. This is useful if you want to ignore incidental small drag movements.

For example:

NotificationListener<OverscrollNotification>(
  onNotification: (OverscrollNotification notification) {
    if (notification.overscroll < 8) {
      // ignore, don't do anything
      return false;
    }

    // do something, for example: load next screen, etc ...

    return true;
  },
  child: PageView(
    controller: _controller,
    children: widget.imagePaths,
  ),
),

8 from above example is result of experiment. You should select the amount which works best for you.

For full example, checkout this blog post.

like image 41
DamirR Avatar answered Nov 17 '25 21:11

DamirR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!