如何在小部件测试中找到屏幕外的ListView子级? [英] How to find off-screen ListView child in widget tests?

查看:81
本文介绍了如何在小部件测试中找到屏幕外的ListView子级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ListView中显示多个子项时,如果一个子项不在屏幕上,则无法通过小部件测试找到它.这是一个完整的示例:

When displaying multiple children in a ListView, if a child is off-screen it can't be found by a widget test. Here's a full example:

main.dart

main.dart

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: Test()));
  }
}

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        Container(
          height: 600,
          color: Colors.red,
        ),
        Text("Find me!"),
      ],
    );
  }
}

main_test.dart

main_test.dart

import 'package:flutter_app/main.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets("Find text", (WidgetTester tester) async {
    final testableWidget = App();

    await tester.pumpWidget(testableWidget);

    expect(find.text("Find me!"), findsOneWidget);
  });
}

此测试失败,但是,如果我将main.dart中Container的高度更改为599,它将起作用.

This test fails, however if I change the height of the Container in main.dart to 599 it works.

有人知道为什么会这样吗?是虫子吗?有办法解决吗?

Anyone know why this happens? Is it a bug? Is there a way around it?

推荐答案

测试的行为应与应用程序的行为相同,否则,测试将变得无用(因为您没有测试实际行为). 因此,这不是错误.

Tests should behave as your app would do, otherwise, your tests become useless (since you're not testing the real behavior). As such, this is not a bug.

您必须在测试内部手动滚动ListView,以使其加载更多小部件.

You have to manually scroll the ListView inside your tests to make it load more widgets.

这可以使用tester完成:

final gesture = await tester.startGesture(Offset.zero /* THe position of your listview */ );
// Manual scroll
await gesture.moveBy(const Offset(0, 100));

await tester.pump(); // flush the widget tree 

这篇关于如何在小部件测试中找到屏幕外的ListView子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆