Lit*_*key 7 testing scroll flutter
我有一个以 ScrollController 作为控制器的 ListView.builder:
_buildListView(state) => ListView.builder(
itemBuilder: (_, int index) => _draw(index, state),
itemCount: state.count
controller: _scrollController,
);
Run Code Online (Sandbox Code Playgroud)
我向控制器添加了一个侦听器:
View() {
_scrollController.addListener(_onScroll);
}
Run Code Online (Sandbox Code Playgroud)
我想测试 _onScroll 函数:
void _onScroll() {
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
if (maxScroll - currentScroll <= _scrollThreshold) {
_bloc.dispatch(Fetch());
}
}
Run Code Online (Sandbox Code Playgroud)
但我不知道我如何测试它。这是我到目前为止尝试过的:
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();
...
)}
Run Code Online (Sandbox Code Playgroud)
但它根本不调用那个函数。
Gui*_*lva 21
对于那些使用新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
);
Run Code Online (Sandbox Code Playgroud)
您可以在测试中创建一个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();
Run Code Online (Sandbox Code Playgroud)
如果将 key 参数传递给构建器:
ListView.builder(key: Key('ListViewKey'),...);
Run Code Online (Sandbox Code Playgroud)
然后按键查找:
await tester.drag(find.byKey(Key('ListViewKey')), const Offset(0.0, -300));
await tester.pump();
Run Code Online (Sandbox Code Playgroud)
将工作。
可以使用 来测试滚动dragUntilVisible
,它会滚动小部件直到它在屏幕上可见,只需确保添加了正确的增量以垂直或水平移动它。
final expectedWidget = find.byText("Find me!");
await tester.dragUntilVisible(
expectedWidget, // what you want to find
find.byType(ListView),
// widget you want to scroll
const Offset(0, 500) // delta to move
);
Run Code Online (Sandbox Code Playgroud)