개발일기

📚 Flutter 위젯 시리즈: GridView 완전 정복

뱅우 2025. 6. 30. 11:21
반응형

Flutter에서 이미지 갤러리, 상품 목록, 카드 뷰 등 격자 형태 레이아웃이 필요할 때 가장 많이 쓰는 위젯이 GridView입니다.
이번 글에서는 GridView의 기본 구조부터 다양한 구현 방법까지 한 번에 정리합니다.


✅ 1. GridView 기본 구조

GridView는 리스트 뷰와 달리, 한 행에 여러 아이템을 가로로 배치할 수 있습니다.


GridView.count(
  crossAxisCount: 2, // 한 줄에 2개씩
  children: [
    Container(color: Colors.red, height: 100),
    Container(color: Colors.blue, height: 100),
    Container(color: Colors.green, height: 100),
    Container(color: Colors.yellow, height: 100),
  ],
)

✔️ crossAxisCount: 가로 열 수를 설정합니다.


✅ 2. GridView.builder로 동적 그리드

동적으로 데이터 리스트를 생성할 때는 GridView.builder를 사용합니다.


GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 3, // 가로 3칸
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
  ),
  itemCount: 20,
  itemBuilder: (context, index) {
    return Container(
      color: Colors.amber,
      child: Center(child: Text('Item $index')),
    );
  },
)

✔️ gridDelegate를 통해 그리드 간격, 열 수를 세부 조정할 수 있습니다.


✅ 3. SliverGridDelegate 종류

구분 설명
SliverGridDelegateWithFixedCrossAxisCount 열 수 고정
SliverGridDelegateWithMaxCrossAxisExtent 열 너비 최대값으로 자동 계산

예를 들어, 디바이스 크기에 따라 열 수를 자동으로 바꿀 땐 SliverGridDelegateWithMaxCrossAxisExtent를 쓰면 좋습니다.


GridView.builder(
  gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 200, // 아이템 최대 너비
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
  ),
  itemCount: 20,
  itemBuilder: (context, index) {
    return Container(
      color: Colors.pinkAccent,
      child: Center(child: Text('Item $index')),
    );
  },
)

✅ 4. 스크롤 방향 바꾸기

기본 스크롤은 세로지만, scrollDirection을 바꿔 가로로 만들 수도 있습니다.


GridView.count(
  scrollDirection: Axis.horizontal,
  crossAxisCount: 1,
  children: List.generate(10, (index) {
    return Container(
      width: 150,
      margin: EdgeInsets.all(8),
      color: Colors.teal,
      child: Center(child: Text('Item $index')),
    );
  }),
)

✅ 5. 언제 GridView를 쓸까?

  • 이미지 갤러리
  • 상품 목록
  • 카드 뷰 레이아웃
  • 비슷한 형태의 반복 아이템

✔️ 동적 목록 + 스크롤 + 격자 → 무조건 GridView!


📌 다음 편 예고

  • 👉 위젯 시리즈: Flutter Sliver 위젯과 CustomScrollView 활용법
반응형