Search code examples
testingscrollflutter

Flutter: how to test the scroll


I have a ListView.builder with a ScrollController as controller:

  _buildListView(state) => ListView.builder(
        itemBuilder: (_, int index) => _draw(index, state),
        itemCount: state.count
        controller: _scrollController,
      );

I add a listener to the controller:

  View() {
    _scrollController.addListener(_onScroll);
  }

I would like to test the _onScroll function:

 void _onScroll() {
    final maxScroll = _scrollController.position.maxScrollExtent;
    final currentScroll = _scrollController.position.pixels;
    if (maxScroll - currentScroll <= _scrollThreshold) {
      _bloc.dispatch(Fetch());
    }
  }

But I don't know how can I test it. This is what I tried so far:

  testWidgets('Should test the scroll',
      (WidgetTester tester) async {
await tester.pumpWidget(generateApp());
    await tester.pump();
    await tester.drag(find.byType(ListView), const Offset(0.0, -300));
    await tester.pump();
...

)}

but it doesn't call at all that function.


Solution

  • You can create a TestGesture in your tests and perform a scroll that way.

    final gesture = await tester.startGesture(Offset(0, 300)); //Position of the scrollview
    await gesture.moveBy(Offset(0, -300)); //How much to scroll by
    await tester.pump();