mohammad
mohammad

Reputation: 2900

How to notice when user released his/her finger from scrolling

I have a listView.Builder and want to do certain calculation based on position of scrollController when user released his/her finger on the screen?

the calculation part is easy in flutter but How can I notice when user released his finger from scrolling to do some action ?

Upvotes: 2

Views: 756

Answers (2)

Jannie Theunissen
Jannie Theunissen

Reputation: 30154

This worked for me:


class _YourScreenState extends State<YourScreen> {
  bool _isDragging = false;
  ScrollUpdateNotification _notification;

  @override
  Widget build(BuildContext context) {
    return NotificationListener<ScrollUpdateNotification>(
      onNotification: (notification) {
        _notification = notification;
        if (_hasLiftedFinger) {
          // do your thing
        }

        _setDraggingState();
        // confidently use _isDragging here

        return false;
      },
      child: YourListView(),
    );
  }

  void _setDraggingState() {
    if (_hasLoweredFinger) {
      _isDragging = true;
      return;
    }

    if (_hasLiftedFinger) {
      _isDragging = false;
    }
  }

  bool get _hasLoweredFinger => (!_isDragging && _notification.dragDetails != null);

  bool get _hasLiftedFinger => (_isDragging && _notification.dragDetails == null);
}

Upvotes: 3

Hamed Hamedi
Hamed Hamedi

Reputation: 1546

Use NotificationListener Widget. Here is a short clip about it.

The code you may want would look like this:

@override
Widget build(BuildContext context) {    
    return NotificationListener<ScrollNotification>(
        onNotification: (notification) {
            if (notification is ScrollStartNotification) {
                debugPrint('Started');
            }
            if (notification is ScrollUpdateNotification) {
                debugPrint('Updated');
            }
            if (notification is ScrollEndNotification) {
                debugPrint('Ended');
            }
            return false;
        },
        child: YourListView(),
    );
}   

Upvotes: 2

Related Questions