How to detect all clicks in Scaffold ScrollBar body

148 views Asked by At

I want to detect all clicks, scrolls, etc. There will be a counter for this. How can I do this?

My code:

return Scaffold(
          body: Scrollbar(
            child: Column(
              children: [
                Expanded(
                  child: CustomScrollView(
....

This answer does not solve my problem because it uses different body: https://stackoverflow.com/a/60163647/7880054

body: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => print('Tapped'),
          child: QQBody(),
        ),

How can I achieve detecting all clicks & scrolls?

1

There are 1 answers

2
Hamed On

You can wrap your widget with a GestureDetector and NotificationListener<ScrollNotification> to detect scroll changes like this:

import 'package:flutter/material.dart';

void main() {
  runApp(const App());
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) => const MaterialApp(home: HomePage());
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int tapCount = 0;
  int scrollCount = 0;

  @override
  Widget build(BuildContext context) => GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          setState(() => tapCount++);
          print('Tapped');
        },
        child: Scaffold(
          appBar: AppBar(title: const Text('Click and Scroll Counter')),
          body: NotificationListener<ScrollNotification>(
            onNotification: (scrollNotification) {
              if (scrollNotification is ScrollStartNotification ||
                  scrollNotification is ScrollUpdateNotification) {
                setState(() => scrollCount++);

                print('Scrolled');
              }

              return false;
            },
            child: Scrollbar(
              child: ListView.builder(
                itemCount: 100,
                itemBuilder: (context, index) =>
                    ListTile(title: Text('Item $index')),
              ),
            ),
          ),
          bottomNavigationBar: BottomAppBar(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text('Taps: $tapCount'),
                  Text('Scrolls: $scrollCount'),
                ],
              ),
            ),
          ),
        ),
      );
}