본문 바로가기
Mobile APP/Flutter

[Flutter] ListView.builder Exception caught by rendering library 오류

by 흐암졸령 2022. 1. 6.
반응형

[문제점]

 플러터에서 ListView.builder를 사용하려고 하는데 다음 오류가 나오면서 위젯이 제대로 나오지 않았다.

Exception caught by rendering library

이때의 코드는 아래와 같았다.

class ListViewExample extends StatelessWidget {
  const ListViewExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListView.builder(
          itemBuilder: (context, index) {
            return Text(index.toString());  
          },
          itemCount: 5,
        ),
      ],
    );
  }
}

 

[해결방법]

 위 코드가 오류가 나왔던 이유는 Row or Column안에 children으로 ListView.builder가 들어가 있기 때문이다. 이때 ListView.builder의 크기가 정해져 있지 않기 때문에 오류가 생겼다. 그러면 크기를 정확하게 정해주면 문제가 해결된다. ListView.builder를 Expanded로 감싸주어서 크기를 전체로 정해주던가 SizedBox를 한 다음에 height를 주면 된다. Expanded로 감싸는 것을 코드로 보면 아래와 같다.

class ListViewExample extends StatelessWidget {
  const ListViewExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
            child: ListView.builder(
            itemBuilder: (context, index) {
              return Text(index.toString());  
            },
            itemCount: 5,
          )
        )
      ],
    );
  }
}
반응형

댓글