Flutter GridView ListView


Flutter에서 GridViewListView는 스크롤 가능한 목록을 만드는 데 사용되는 중요한 위젯입니다. 이 두 위젯은 다양한 방식으로 데이터를 표시하고, 사용자가 스크롤하여 아이템을 탐색할 수 있도록 합니다. 각각의 특성과 사용 예시를 살펴보겠습니다.

ListView

ListView는 세로 방향으로 스크롤 가능한 목록을 생성하는 위젯입니다. 아이템은 세로로 배치되며, 스크롤을 통해 사용자가 목록을 위아래로 이동할 수 있습니다.

기본 ListView 예제

ListView(
  children: <Widget>[
    ListTile(title: Text('Item 1')),
    ListTile(title: Text('Item 2')),
    ListTile(title: Text('Item 3')),
    // Add more ListTile widgets as needed
  ],
)

ListView.builder를 이용한 동적 목록 생성 예제

ListView.builder(
  itemCount: 20, // 아이템 개수
  itemBuilder: (context, index) {
    return ListTile(
      title: Text('Item $index'),
    );
  },
)

ListView의 주요 특징:

  • 유연성: 크기가 정해지지 않은 목록을 효과적으로 처리할 수 있습니다.
  • 성능: 화면에 보이는 아이템만 렌더링되기 때문에 메모리와 성능 면에서 효율적입니다.
  • ScrollPhysics: 스크롤 동작을 커스터마이즈할 수 있는 다양한 ScrollPhysics를 제공합니다.

GridView

GridView는 2차원 그리드 형태의 스크롤 가능한 목록을 생성하는 위젯입니다. 행과 열에 따라 아이템이 배치되며, 사용자는 가로로 스크롤하여 목록을 탐색할 수 있습니다.

기본 GridView 예제

GridView.count(
  crossAxisCount: 2, // 한 줄에 표시할 열의 개수
  children: <Widget>[
    Container(color: Colors.red),
    Container(color: Colors.green),
    Container(color: Colors.blue),
    // Add more Container widgets as needed
  ],
)

GridView.builder를 이용한 동적 그리드 생성 예제

GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2,
    mainAxisSpacing: 10.0,
    crossAxisSpacing: 10.0,
  ),
  itemBuilder: (context, index) {
    return Container(
      color: Colors.teal[100 * (index % 9)],
      child: Center(
        child: Text('Grid Item $index'),
      ),
    );
  },
  itemCount: 20, // 아이템 개수
)

GridView의 주요 특징:

  • 2차원 레이아웃: 행과 열을 이용하여 데이터를 표시합니다.
  • 스크롤 방향: 가로로 스크롤하여 목록을 탐색할 수 있습니다.
  • 레이아웃 제어: SliverGridDelegate를 사용하여 그리드의 레이아웃을 세밀하게 제어할 수 있습니다.

ListView와 GridView의 결합 예제

ListViewGridView를 함께 사용하여 복잡한 레이아웃을 구성할 수 있습니다. 예를 들어, ListView의 아이템으로 GridView를 포함할 수 있습니다.

ListView.builder(
  itemCount: 5,
  itemBuilder: (context, index) {
    return Card(
      margin: EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          Text('List Item $index'),
          GridView.count(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            crossAxisCount: 2,
            children: List.generate(4, (subIndex) {
              return Container(
                color: Colors.purple[100 * (subIndex % 9)],
                child: Center(
                  child: Text('Grid Item $subIndex'),
                ),
              );
            }),
          ),
        ],
      ),
    );
  },
)

결론

Flutter의 ListViewGridView는 스크롤 가능한 목록을 구성하는 데 매우 유용한 위젯입니다. 각각의 특성을 활용하여 다양한 데이터 표시 요구에 맞는 UI를 구현할 수 있습니다. ListView는 세로 방향의 목록을, GridView는 2차원 그리드 형태의 목록을 만들 때 사용됩니다. 이들을 적절히 조합하여 사용하면 효율적이고 유연한 Flutter 애플리케이션을 개발할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *