跳到主内容

处理滚动

如何在 Widget 测试中处理滚动。

许多应用都包含内容列表,从电子邮件客户端到音乐应用等等。要使用 Widget 测试验证列表是否包含预期的内容,你需要一种滚动列表来查找特定项的方法。

要通过集成测试滚动列表,请使用 WidgetTester 类提供的方法,该类包含在 flutter_test 软件包中。

在本篇指南中,你将学习如何滚动列表以验证特定 Widget 是否显示,以及不同方法的优缺点。

本示例将采取以下步骤

  1. 创建一个包含列表项的应用。
  2. 编写一个测试来滚动列表。
  3. 运行测试。

1. 创建一个包含列表项的应用

#

本指南将构建一个显示长列表的应用。为了让指南专注于测试,我们将使用在使用长列表指南中创建的应用。如果你不确定如何处理长列表,请参阅该指南进行了解。

为要在集成测试中交互的 Widget 添加 Key。

dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp(items: List<String>.generate(10000, (i) => 'Item $i')));
}

class MyApp extends StatelessWidget {
  final List<String> items;

  const MyApp({super.key, required this.items});

  @override
  Widget build(BuildContext context) {
    const title = 'Long List';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(title: const Text(title)),
        body: ListView.builder(
          // Add a key to the ListView. This makes it possible to
          // find the list and scroll through it in the tests.
          key: const Key('long_list'),
          itemCount: items.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(
                items[index],
                // Add a key to the Text widget for each item. This makes
                // it possible to look for a particular item in the list
                // and verify that the text is correct
                key: Key('item_${index}_text'),
              ),
            );
          },
        ),
      ),
    );
  }
}

2. 编写一个测试来滚动列表

#

现在,你可以编写测试了。在此示例中,滚动列表并验证特定项是否存在于列表中。WidgetTester 类提供了 scrollUntilVisible() 方法,该方法会滚动列表直到指定的 Widget 可见。这非常有用,因为列表中项的高度可能会根据设备而变化。

无需假定你知道列表中所有项的高度,也不必假定特定 Widget 在所有设备上都会渲染,scrollUntilVisible() 方法会重复滚动列表直到找到目标内容。

以下代码展示了如何使用 scrollUntilVisible() 方法在列表中查找特定项。此代码位于 test/widget_test.dart 文件中。

dart

// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:scrolling/main.dart';

void main() {
  testWidgets('finds a deep item in a long list', (tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(
      MyApp(items: List<String>.generate(10000, (i) => 'Item $i')),
    );

    final listFinder = find.byType(Scrollable);
    final itemFinder = find.byKey(const ValueKey('item_50_text'));

    // Scroll until the item to be found appears.
    await tester.scrollUntilVisible(itemFinder, 500.0, scrollable: listFinder);

    // Verify that the item contains the correct text.
    expect(itemFinder, findsOneWidget);
  });
}

3. 运行测试

#

在项目根目录下使用以下命令运行测试

flutter test test/widget_test.dart