본문 바로가기
스파르타 코딩 클럽 내일배움캠프 6기/[Flutter 트랙] 앱개발 종합반

[Flutter 트랙] 앱개발 종합반 2-3 - PageView

by 앱 창업 부트캠프 2025. 3. 4.

Flutter PageView 위젯

PageView 위젯은 페이지를 스와이프(Swipe)하여 전환하는 기능을 제공합니다. 대표적인 사용 예시는 앱 튜토리얼, 슬라이드 쇼, 카드형 UI 등에서 사용됩니다.


1. PageView 기본 개념

PageView 위젯을 활용하면 여러 개의 페이지를 가로 또는 세로 방향으로 넘길 수 있습니다.

PageView 특징

  • 페이지를 가로 또는 세로 방향으로 스와이프 가능
  • 무한 페이지 전환, 정지(Snap) 등 다양한 옵션 제공
  • 컨트롤러(PageController)를 사용하여 페이지 이동 가능
  • 이벤트 감지 (onPageChanged 등) 기능 제공

PageView 기본 예제


import 'package:flutter/material.dart';

void main() {
    runApp(MaterialApp(home: PageViewExample()));
}

class PageViewExample extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            body: PageView(
                children: [
                    Container(color: Colors.red, child: Center(child: Text("1", style: TextStyle(fontSize: 50, color: Colors.white)))),
                    Container(color: Colors.blue, child: Center(child: Text("2", style: TextStyle(fontSize: 50, color: Colors.white)))),
                    Container(color: Colors.green, child: Center(child: Text("3", style: TextStyle(fontSize: 50, color: Colors.white)))),
                ],
            ),
        );
    }
}

➡️ 손가락으로 좌우로 스와이프하면 페이지가 전환됩니다.


2. PageView 옵션 (스크롤 방향 설정)

기본적으로 PageView가로 스크롤을 지원합니다. 하지만 세로 스크롤(vertical scroll) 도 가능하며, 옵션을 변경하면 쉽게 적용할 수 있습니다.

세로 스크롤 PageView 예제


PageView(
    scrollDirection: Axis.vertical,  // 기본값은 Axis.horizontal
    children: [
        Container(color: Colors.red, child: Center(child: Text("Page 1"))),
        Container(color: Colors.blue, child: Center(child: Text("Page 2"))),
        Container(color: Colors.green, child: Center(child: Text("Page 3"))),
    ],
),

➡️ scrollDirection: Axis.vertical 을 설정하면 위-아래로 스크롤 됩니다.


3. PageController 사용 (버튼 클릭 시 페이지 이동)

PageController를 사용하면 버튼을 눌러서 특정 페이지로 이동할 수 있습니다.

특정 페이지로 이동하는 예제


class PageViewWithController extends StatefulWidget {
    @override
    _PageViewWithControllerState createState() => _PageViewWithControllerState();
}

class _PageViewWithControllerState extends State<PageViewWithController> {
    final PageController _controller = PageController();  // 컨트롤러 생성

    void goToPage(int page) {
        _controller.jumpToPage(page);  // 특정 페이지로 이동
    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(title: Text("PageView Controller Example")),
            body: Column(
                children: [
                    Expanded(
                        child: PageView(
                            controller: _controller,  // 컨트롤러 연결
                            children: [
                                Container(color: Colors.red, child: Center(child: Text("Page 1"))),
                                Container(color: Colors.blue, child: Center(child: Text("Page 2"))),
                                Container(color: Colors.green, child: Center(child: Text("Page 3"))),
                            ],
                        ),
                    ),
                    ElevatedButton(
                        onPressed: () => goToPage(1), // 버튼 클릭 시 2페이지로 이동
                        child: Text("2페이지로 이동"),
                    ),
                ],
            ),
        );
    }
}

➡️ 버튼을 클릭하면 2번째 페이지(1번 인덱스)로 이동합니다.


4. PageView 이벤트 감지 (onPageChanged)

현재 페이지가 변경될 때 이벤트를 감지하고 싶다면 onPageChanged 옵션을 사용하면 됩니다.

현재 페이지 감지 예제


PageView(
    onPageChanged: (index) {
        print("현재 페이지: $index");  // 페이지가 변경될 때마다 콘솔에 출력
    },
    children: [
        Container(color: Colors.red, child: Center(child: Text("Page 1"))),
        Container(color: Colors.blue, child: Center(child: Text("Page 2"))),
        Container(color: Colors.green, child: Center(child: Text("Page 3"))),
    ],
),

➡️ 페이지가 변경될 때마다 onPageChanged 콜백이 실행됩니다.


5. PageView의 스냅핑(Snapping) 기능

PageView는 기본적으로 페이지가 자동으로 스냅됩니다 (즉, 한 페이지 단위로 이동). 하지만, 이를 비활성화할 수도 있습니다.

스냅핑 기능 비활성화 예제


PageView(
    pageSnapping: false,  // false로 설정하면 사용자가 조절 가능
    children: [
        Container(color: Colors.red, child: Center(child: Text("Page 1"))),
        Container(color: Colors.blue, child: Center(child: Text("Page 2"))),
        Container(color: Colors.green, child: Center(child: Text("Page 3"))),
    ],
),

➡️ pageSnapping: false 설정 시 사용자가 원하는 만큼만 스크롤할 수 있습니다.


6. 결론

  • PageView페이지 전환을 위한 강력한 Flutter 위젯
  • 기본적으로 가로 스크롤이지만, 세로 스크롤도 가능
  • PageController를 사용하면 버튼 클릭으로 특정 페이지로 이동 가능
  • onPageChanged를 사용하여 페이지 변경 이벤트 감지 가능
  • pageSnapping을 조정하여 스크롤 동작을 커스터마이징 가능

다음 강의에서는 ListView 위젯을 살펴보겠습니다! 🚀