LoginSignup
0
0

More than 1 year has passed since last update.

【Flutter】テストで、子ウィジェットを取得する方法

Posted at

こんなアプリがありました

ソースコードはこちら。

Flutterの初期コードを改造し、1増えるボタン2増えるボタンがあります。

Card getCard(String title, int addValue, Key key) {
  return Card(
    key: key, //Keyはここにある!
    child: Column(
      children: [
        Text(title), //引数の文字をタイトルに
        OutlinedButton(
            onPressed: () {
              _incrementCounter(addValue); //カウンターの値を引数の値分増やす
            },
            child: const Text("ボタン"),)
      ],
    ),
  );
}

カードはこのような実装で作られています。

問題点

テストを作る際に、find.text("ボタン")してしまうと、2つ見つかってしまいます。
image.png

解決策

ここで、KeyはOneButtonTwoButtonと分かれていますので、find.byKey()を利用して、孫要素であるTextを探してtester.tap()をしてみようと思います。

成果物

上記リンクのようなソースコードになりました。

//KeyからWidgetを取得する
var oneButtonParent = find.byKey(const Key("OneButton")); 
//ボタンのテキストを取得する
var buttonText = find.text("ボタン");
//親要素から子要素を取得する
var oneButtonText = find.descendant(of: oneButtonParent, matching: buttonText);

一番下のfind.descendantが子孫を取得する部分なのですが、至ってシンプルです。

find.descendant(of: 親要素が含まれるFinder, matching: 探したいものが含まれるFinder)

としてあげることで、親要素の子孫要素から絞り込んだFinderを生成します。

公式ドキュメントはこちら。

ちなみに逆バージョンで親要素を取得するものもあります。

0
0
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
0
0