Help us understand the problem. What is going on with this article?

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

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が毎度作成されないようにするなどの対応が必要です。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした