2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FlutterでTextField(TextFormField)を使うと、大量に再描画される

Last updated at Posted at 2022-07-27

概要

TextFieldもしくはTextFormFieldを設置すると、大量(数十回)に再描写(build)される
※厳密には、MaterialPageRouteでpush(遷移)した先に、TextFieldを設置すると、同現象が発生する

この現象により、FutureBuilderやStreamBuilderと組み合わせると
「TextFieldが更新(focusやchange)される→再描画が走る→Future/StreamBuilderが走る」というループで、永遠にTextFieldへの入力が出来なかったりする。

サンプル

// 遷移元
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => Page())
);

// 遷移先
class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextField(
        // このテキストフィールドがあると大量に再描画(rebuild)される
      ),
    );
  }
}

対応方法

pushする直前にViewをインスタンス化する

通常、このように遷移するが

Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => Page())
);

↓ こうする

final page = Page();  // インスタンス化
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => page)
);

こうする事で、遷移先のPageに設置したtextFieldにfocusが当たっても大量のrebuildが走らなくなる

参考

Opening or closing a TextField causes MaterialPageRoute to rebuild the page #37878
https://github.com/flutter/flutter/issues/37878

2
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?