2


我在尝试测试我的 Flutter 应用程序时遇到了错误。我有一个自定义小部件,它位于小部件的底部(在第一个视口之外)CustomScrollView。在我的测试中,我想验证它确实存在。
我已经尝试过使用WidgetTester.scrollUntilVisibleas well WidgetTester.drag(就像在颤振框架的测试中所做的那样)。此外,我试图用它来重构我的测试,FlutterDriver这完全把其他一切都搞砸了。
如何滚动到CustomScrollView测试内部的底部?
这个最小复制显示了包含CustomScrollViewContainer 小部件的应用程序,该小部件具有一个屏幕的高度(因此我要查找的小部件不在初始视图中)

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

4

1 回答 1

2

我遇到了同样的问题,最终我使用了 dragUntilVisible() 方法而不是 scrollUntilVisible()。

向下滚动直到小部件可见的示例:

await tester.dragUntilVisible(myWidget, customScrollView, Offset(0, -500));
于 2021-06-30T08:27:18.117 回答