💬

【逆引き】Flutterのテストでウィジェットを探す方法

に公開

Flutterのウィジェットテストでウィジェットを探す方法をまとめました。
expect(find.xxx, findsOneWidget);を書くときのfind.xxxの部分です)

keyで探す

ウィジェットにつけたキーで探すには、find.byKeyを使う

find.byKey(const Key('target'))
example.dart
const Scaffold(
  body: Center(
    key: Key('target'),  // keyがついている
    child: Text('Find'),
  ),
example_test.dart
  testWidgets('find test', (tester) async {
    await tester.pumpWidget(
      const MaterialApp(home: Find()),
    );

    // keyで探す(Centerが見つかる)
    expect(find.byKey(const Key('target')), findsOneWidget);
  });

複数の条件で絞り込む

ウィジェットのオプションなどで絞り込むには、find.byWidgetPredicateを使う

find.byWidgetPredicate((widget) => widget is Image && widget.height == 100);

テキストの内容で絞り込む

ウィジェットのテキストで絞り込むには、完全一致ならfind.textを使う。部分一致ならfind.textContainingが使えて正規表現でも指定可能。

find.text('Hello');
find.textContaining('He');

アイコンで探す

find.byIcon(Icons.menu)

ウィジェットのClassで探す

find.byType(Scaffold);

ウィジェットが複数該当してしまうとき

最初のやつ

find.byType(Column).first

最後のやつ

find.byType(Column).last

n番目

find.byType(Column).at(1)  // 2番目のウィジェット(0オリジン)

Discussion