【发布时间】:2020-07-14 22:34:05
【问题描述】:
我正在为我的屏幕编写一个小部件测试,其中一项要求是测试SliverAppBar 的浮动行为。但是,我无法进行测试,因为 SliverAppBar 不会浮动,尽管相同的代码在真实设备上运行时可以正常工作。
为了在测试期间可视化当前屏幕,我将屏幕与黄金文件(不存在)进行比较,并使用flutter test --update-goldens 运行测试,让测试创建黄金文件,果然SliverAppBar没有出现在HomePage_golden_scroll3.png 中。 SliverAppBar 仅在完全向上滚动时显示(即它的行为就像 floating 是 false。
由于它在真实设备上运行良好,我想知道我的测试有什么问题?
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
SliverAppBar(
floating: true,
title: Text('app bar title'),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('test ' * index)),
childCount: 20,
),
),
],
),
);
}
}
void main() {
testWidgets('AppBar should hide on scroll', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(home: HomePage()));
await expectLater(find.byType(HomePage),
matchesGoldenFile('HomePage_golden_scroll1.png'));
expect(find.byType(SliverAppBar), findsOneWidget);
var scrollableWidget = find.text('test ' * 8);
var originalPosition = tester.getRect(scrollableWidget);
// Scroll down.
final position =
tester.state<ScrollableState>(find.byType(Scrollable)).position;
position.jumpTo(500.0);
await tester.pump();
await expectLater(find.byType(HomePage),
matchesGoldenFile('HomePage_golden_scroll2.png'));
var afterScrollPosition = tester.getRect(scrollableWidget);
// Make sure the scroll worked, i.e. the view is big enough to scroll.
expect(afterScrollPosition.top, lessThan(originalPosition.top));
// Now the AppBar should be hidden.
expect(find.byType(SliverAppBar), findsNothing);
// When scrolling up again, the AppBar should be immediately visible
// again, not only when scrolling up completely.
position.jumpTo(350);
await tester.pump();
await expectLater(find.byType(HomePage),
matchesGoldenFile('HomePage_golden_scroll3.png'));
// AppBar should be visible again.
expect(find.byType(SliverAppBar), findsOneWidget);
});
}
【问题讨论】:
标签: flutter flutter-test