【Flutter】Widgetを抽出するときに『Reference to an enclosing class method cannot be extracted』が出たときの対処法

Flutter
 

現象

VSCodeにてWidgetを自動抽出(Extract)しようとしたときに
以下のようなエラーが出力されてしまうことがある。

このエラーを回避する方法を2つ紹介する。

解決方法

抽出できないパターンは主に2つ。

それらに該当するソースの記述を見直すことで解決される。

抽出しようとするWidgetの中にメソッドが定義されている

以下のソースではColumnのWidgetを抽出(Extract)しようとしたときに
表題のようなエラーが出力される。

weekButtonにて抽出しているメソッドを定義し直すことで解決される。

(略)
        child: Column(
          children: [
            TextField(
              onChanged: ((String value) {
                setState(() {
                  _text = value;
                });
              }),
              onSubmitted: (v) {
                Navigator.of(context).pop(_text);
              },
            ),
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    weekButton('今週'),
                    weekButton('来週'),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    weekButton('2週間後'),
                    weekButton('それ以降'),
                  ],
                ),
              ],
            ),
(略)
  Expanded weekButton(String buttonText) {
    return Expanded(
      (略)
    );
  }
}

抽出しようとするWidgetの中にSetStateにて使用している変数が存在している

以下のソースではChildrenのWidgetを抽出(Extract)しようとしたときに
表題のようなエラーが出力される。

抽出しようとしているChildrenのWidgetの中にsetStateが定義してあると抽出することができない。

一度setStateをコメントアウトして、Widgetを抽出し、抽出先で再度setStateを定義してあげれば良い

(略)
        child: Column(
          children: [
            TextField(
              onChanged: ((String value) {
                setState(() {
                  _text = value;
                });
              }),
              onSubmitted: (v) {
                Navigator.of(context).pop(_text);
              },
            ),
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    weekButton('今週'),
                    weekButton('来週'),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    weekButton('2週間後'),
                    weekButton('それ以降'),
                  ],
                ),
              ],
            ),
(略)
  Expanded weekButton(String buttonText) {
    return Expanded(
      (略)
    );
  }
}

コメント

タイトルとURLをコピーしました