跳到主內容

處理滾動

如何在 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