Search code examples
flutterdartscroll

NotificationListener not working with horizontal ListView.builder in Flutter


My code is:

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(
      home: MyHomePage(),
    ));

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: NotificationListener(
          onNotification: (scrollNotification) {
            print(scrollNotification); 
            return true; 
          },
          child: ListView.builder(
            scrollDirection: Axis.horizontal,  // <= works if replaced by vertical
            itemCount: 2,                      // <= works if replaces by 22
            itemBuilder: (context, index) {
              return const Text("text ");
            },
          ),
        ),
      ),
    );
  }
}

It doesn't generate scrolling event when I scroll.

If I change to Axis.vertical it works as expected.

If I change itemCount to 22 - it works.


Solution

  • You can use physics: AlwaysScrollableScrollPhysics() which force the listview to be scrollable even if it didn't have enough items and this will send inputs to the listener.