颤振:如何测试滚动

时间:2019-05-24 11:29:52

标签: testing scroll flutter

我有一个使用ScrollController作为控制器的ListView.builder:

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

我向控制器添加了一个侦听器:

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

我想测试_onScroll函数:

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

但是我不知道该如何测试。这是我到目前为止尝试过的:

  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();
...

)}

但它根本不调用该函数。

5 个答案:

答案 0 :(得分:2)

对于那些使用新的 flutter_test 库的人,我们还有 dragUntilVisible 方法:

await tester.dragUntilVisible(
    find.text('Earn mana!'), // what you want to find
    find.byKey(ValueKey('OnboardingCarousel')), // widget you want to scroll
    const Offset(-250, 0), // delta to move
);

答案 1 :(得分:1)

如果将关键参数传递给构建器:

protected void afterExecute(Runnable r, Throwable t) {
  super.afterExecute(r, t);
  if (t == null && r instanceof Future<?>) {
    try {
      Object result = ((Future<?>) r).get();
    } catch (CancellationException ce) {
        t = ce;
    } catch (ExecutionException ee) {
        t = ee.getCause();
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt(); // ignore/reset
    }
  }
  if (t != null)
    System.out.println(t);
}

然后按键查找:

ListView.builder(key: Key('ListViewKey'),...);

会工作的。

答案 2 :(得分:0)

您可以在测试中创建TestGesture并以这种方式执行滚动。

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();

答案 3 :(得分:0)

我强烈建议您注意屏幕/拖动运动的“笛卡尔平面”。

让我解释一下:

  1. 你应该使用: 等待 tester.drag(keyCartItemProduct1, Offset(-500.0, 0.0));
  2. 但是,您的“偏移”命令必须遵循与拖动相同的“笛卡尔方向”。

2.1) 因此:(偏移命令使用笛卡尔“方向”) - 让我们看看: a) 左拖动:偏移(-500.0, 0.0) b) 右拖动:偏移(+500.0, 0.0) c) 向上拖动:偏移(0.0, +500.0) d) 向下拖动:Offset(0.0, -500.0)

答案 4 :(得分:0)

作为替代方案,也可以搜索 ListView 小部件本身并检索其滚动控制器以直接操作它:

final listView = tester.widget<ListView>(find.byType(ListView));
final ctrl = listView.controller;
ctrl.jumpTo(ctrl.offset + 300);
await tester.pumpAndSettle(duration);