LoginSignup
1
2

More than 3 years have passed since last update.

[Flutter] LayoutBuilderが無限にビルドされてしまうのを防ぐには

Last updated at Posted at 2020-02-18

Widgetのサイズを取得するために使用されるLayoutBuilderは、その子Widgetがビルドされると、それに伴ってビルドされてしまいます。
したがって、FutureBuilderなど動的にUIを変更するWidgetをLayoutBuilderの子孫に使用するときは注意が必要です。

例えば以下のWidgetはTextがビルドされるごとにLayoutBuilderがリビルドされ、無限にビルドされてしまいます。


 @override
  Widget build(BuildContext context) => LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) => FutureBuilder<Ranking>(
          future: future,
          builder: (BuildContext context, AsyncSnapshot<Ranking> snapshot) {
            if (snapshot.hasError)
              return Text('error');

            if (!snapshot.hasData)
              return Text('loading');

            return Text('done');
          },
        ));

このことはFutureBuilderのリファレレンスの冒頭に書かれています。

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

StatefullWidgetなどを用いてfutureが毎度作成されないようにするなどの対応が必要です。

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