我在尝试测试我的 Flutter 应用程序时遇到了错误。我有一个自定义小部件,它位于小部件的底部(在第一个视口之外)CustomScrollView
。在我的测试中,我想验证它确实存在。
我已经尝试过使用WidgetTester.scrollUntilVisible
as well WidgetTester.drag
(就像在颤振框架的测试中所做的那样)。此外,我试图用它来重构我的测试,FlutterDriver
这完全把其他一切都搞砸了。
如何滚动到CustomScrollView
测试内部的底部?
这个最小复制显示了包含CustomScrollView
Container 小部件的应用程序,该小部件具有一个屏幕的高度(因此我要查找的小部件不在初始视图中)
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Container(
height: MediaQuery.of(context).size.height,
),
),
MyWidget(),
],
)),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SliverToBoxAdapter(
child: Container(
height: 100,
width: 100,
),
);
}
}
这是我最初为查找小部件而编写的测试,当然失败了。
void main() {
testWidgets('main contains mywidget', (WidgetTester tester) async {
// arange
await tester.pumpWidget(MyApp());
// act
final myWidget = find.byType(MyWidget);
// assert
expect(myWidget, findsOneWidget);
});
}
在本次迭代中,我使用了该WidgetTester.scrollUntilVisible
函数,但出现以下错误。
void main() {
testWidgets('main contains mywidget', (WidgetTester tester) async {
// arange
await tester.pumpWidget(MyApp());
// act
final myWidget = find.byType(MyWidget);
final customScrollView = find.byType(CustomScrollView);
await tester.scrollUntilVisible(myWidget, 100,
scrollable: customScrollView);
await tester.pump();
// assert
expect(myWidget, findsOneWidget);
});
}
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following _CastError was thrown running a test:
type 'CustomScrollView' is not a subtype of type 'Scrollable' in type cast
When the exception was thrown, this was the stack:
#0 WidgetController.widget (package:flutter_test/src/controller.dart:66:44)
#1 WidgetController.scrollUntilVisible.<anonymous closure> (package:flutter_test/src/controller.dart:995:15)
#2 WidgetController.scrollUntilVisible.<anonymous closure> (package:flutter_test/src/controller.dart:993:39)
#5 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41)
#6 WidgetController.scrollUntilVisible (package:flutter_test/src/controller.dart:993:27)
#7 main.<anonymous closure> (file:///C:/Users/X/test_example/test/main_test.dart:12:18)
<asynchronous suspension>
<asynchronous suspension>
(elided 3 frames from dart:async and package:stack_trace)
我感谢任何有关如何解决此问题并成功测试我的帮助或建议CustomScrollView