Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@HiroyukiTamura

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

More than 1 year has passed since last update.

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

2
Help us understand the problem. What is going on with this article?
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.
Sign Up
If you already have a Qiita account Login
2
Help us understand the problem. What is going on with this article?