LoginSignup
2
2

More than 3 years have passed since last update.

FlutterのWidgetTestでContextを得る

Posted at

下記環境でFlutterアプリを開発中です。

ツールなど バージョンなど
MacBook Air Early2015 macOS Mojave 10.14.5
Android Studio 3.6.1
Java 1.8.0_131
Flutter 1.12.13+hotfix.5
Dart 2.7.0

FlutterのWidgetTestを書いていて、BuildContextが必要になってその方法を調べたので、覚え書き。

tester.elementを使う

例えば、FooWidget(やその子ウィジェット)のBuildContextが必要な場合は、以下のようにします。


  final BuildContext context = tester.element(
      find.byWidgetPredicate((Widget widget) => widget is ListView));

ウィジェットの特定に条件がたくさんで長くなるときは、分けて書く方が見やすいかも。(好みの問題)

  WidgetPredicate predicate = (Widget widget) => 
      widget is FooWidget && 
      widget.data=='Foo' &&
      ....;

  final BuildContext context =
      tester.element(find.byWidgetPredicate(predicate));

ちなみに、必要になったシチュエーションとしては、

  • BoxDecorationBordercolorTheme.ofで取得できる色

を条件としたかったためで、こんな風にcontextを使いました。

    WidgetPredicate predicate = (Widget widget) =>
      widget is Container &&
      widget.decoration is BoxDecoration &&
      (widget.decoration as BoxDecoration).border ==
          Border(
            left: BorderSide(
              width: 0.5,
              color: Theme.of(context).dividerColor,
            ),
            top: BorderSide(
              width: 0.5,
              color: Theme.of(context).dividerColor,
            ),
          );

以上です。

参考サイト

flutter自身(ダイアログ)のテストコード内にありました。
https://github.com/flutter/flutter/blob/master/packages/flutter/test/material/dialog_test.dart

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2