[Flutter] ListView 에러 해결하기

이희령·2024년 5월 13일
0

Flutter

목록 보기
3/6

리팩토링

  • 강의에서는 간단하게 Column으로 리스트를 구현했지만, 데이터의 양이 꽤 되기 때문에 ListView로 최적화를 해보고 싶었다.
  • 하지만 Column 위젯 안에서 ListView를 사용하는 과정에서 ListView의 높이를 계산하는 문제로 에러가 발생했다.

에러 메세지

  • RenderFlex children have non-zero flex but incoming height constraints are unbounded.
  • ListView.builder 위젯에 별도의 설정을 하지 않을 경우 발생하는 에러

  • Failed assertion: line 1972 pos 12: 'hasSize'
  • Cannot hit test a render box with no size.
  • ListView.builder 위젯을 Expanded 위젯으로 감쌀 경우 발생하는 에러

에러 해결

// as is
FutureBuilder(
  future: widget.episodes,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Column(
        children: [
        for (var episode in snapshot.data!)
      Episode(episode: episode, webtoonId: widget.id)
      ],
        );
    }
    return Container();
  },
),

// to be
FutureBuilder(
  future: widget.episodes,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return ListView.builder(
        shrinkWrap: true, // 리스트 자식 높이 크기의 합 만큼 영역 고정
        physics:
        const NeverScrollableScrollPhysics(), // 리스트뷰 내에서 스크롤 안되도록 설정
        itemCount: snapshot.data!.length,
          itemBuilder: (context, index) {
            var episode = snapshot.data![index];
            return Episode(episode: episode, webtoonId: widget.id);
          },
            );
    }
    return Container();
  },
),
  • 예전에 ListView.builder 위젯을 사용할 때는 Expanded() 위젯으로 감싸서 해결했었는데 이번에는 해결되지 않았다.
  • ListView 위젯의 shrinkWrap: true 속성을 사용하면 ListView의 크기를 현재 표시되는 아이템들의 크기에 맞게 자동으로 조절해준다. 하지만 이를 위해 모든 아이템을 미리 렌더링해야 하기 때문에 최적화를 위해 ListView.builer를 사용하는 의도와는 다르게 성능에 영향을 미칠 수 있다고 한다.
  • shrinkWrap: true 속성을 사용하면 리스트뷰 안에서만 스크롤이 가능하기 때문에 이를 해결하려면 physics: const NeverScrollableScrollPhysics() 속성까지 추가해야 바디 전체의 스크롤을 사용할 수 있게 된다.

References

profile
Small Steps make a Big Difference.🚶🏻‍♀️

0개의 댓글