arcanum_jp’s blog

おっさんの日記

FlutterでListViewで死ぬ

普通にListView.builderで構築したところこんなエラーがでて画面のListViewが構築できない・・・

RenderBox was not laid out: RenderRepaintBoundary#da13e relayoutBoundary=up2 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1927 pos 12: 'hasSize'


Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.md


ソースはこんな感じ

    return Scaffold(
      ... 省略
      body: Column(
        children: [
          Container(...省略),
          Container(...省略),
          ListView.builder(
              itemCount: _searchResults.length,
              itemBuilder: (context, index) {
                return Card(
                  child: Padding(
                    child: Text(_searchResults[index].showDate, style: TextStyle(fontSize: 22.0),),
                    padding: EdgeInsets.all(20.0),
                  ),
                );
              }
          ),
        ],
      ),
   );

  }

エラーメッセージの下の方にFlutterでエラーが出てるからイシューたててね💖的なの書いてありギョッとしてたんだけど、あぁ、、イシュー立てるのか・・・めんどくさい・・・と絶望的になってたのですがエラーメッセージ内の「RenderBox was not laid out: RenderRepaintBoundary」で検索すると以下のStackOverflowが・・・


stackoverflow.com

The problem is that you are placing the ListView inside a Column/Row. The text in the exception gives a good explanation of the error.

To avoid the error you need to provide a size to the ListView inside.

I propose you this code that uses an Expanded to inform the horizontal size (maximum available) and the SizedBox (Could be a Container) for the height:

なるほどーーColumの中に直接ListView書くとビューのサイズがわからんので構築できないと・・・さすがStackoverflowさんです。気を取り直して修正してOKでした。
先のソースのListView.builder...の部分をExpanded-SizeBoxのコンテナで囲んでます。

          Expanded(
              child: SizedBox(
                height: 200,
                child: ListView.builder(
                    itemCount: _searchResults.length,
                    itemBuilder: (context, index) {
                      return Card(
                        child: Padding(
                          child: Text(_searchResults[index].showDate, style: TextStyle(fontSize: 22.0),),
                          padding: EdgeInsets.all(20.0),
                        ),
                      );
                    }
                ),
              ),
          ),

件のStackoverflowのエラーの問題は自分のとは別の問題みたいなんだけど、問題解決できました。
ちゃんちゃん