[Flutter] CarouselSlider로 여러 이미지 보여주기

IE·2023년 1월 30일
1

Flutter

목록 보기
3/7
post-thumbnail

플러터로 어플리케이션을 만들던 중, 여러 이미지를 한 번에 보여주는 페이지를 만들 일이 생겼다.

잘 보일지는 모르겠지만 썸네일은 앱 화면을 일부 캡처한 사진이다.

이미지 배열이 주어지면 옆으로 슬라이드 하며 넘길 수 있는 ImageView를 제작하고, Indicator를 사용해 몇 번째 사진인지 확인할 수 있도록 작성했다.

이 라이브러리를 사용하기 위해서 우선 pubspec.yalm 파일에 아래의 의존성을 추가해준다.

// pubspec.yalm
dependencies:
  flutter:
    sdk: flutter
  ...
  carousel_slider: ^4.2.1			// 여기
  smooth_page_indicator: ^1.0.0+2	// 여기

의존성 추가가 완료되고 나면, 해당 라이브러리를 사용할 수 있도록 이 위젯이 들어갈 파일에 import를 해준다.

그 후에 원하는 이미지 배열을 images라는 변수명으로 선언하고, 이미지 슬라이더와 인디케이터 위젯을 아래와 같이 생성한다.

Widget imageSlider(path, index) => Container(
        width: double.infinity,
        height: 240,
        color: Colors.grey,
        child: Image.asset(path, fit: BoxFit.cover),
      );

  Widget indicator() => Container(
      margin: const EdgeInsets.only(bottom: 20.0),
      alignment: Alignment.bottomCenter,
      child: AnimatedSmoothIndicator(
        activeIndex: activeIndex,
        count: images.length,
        effect: JumpingDotEffect(
            dotHeight: 6,
            dotWidth: 6,
            activeDotColor: Colors.white,
            dotColor: Colors.white.withOpacity(0.6)),
      ));

당연하지만 인디케이터의 크기 및 색상 등 디자인적인 부분은 본인의 취향껏 바꾸면 된다.

image 위젯부터 간단히 설명하겠다.

  • width: double.infinity -> 화면 너비에 맞도록 위젯 너비 설정
  • fit: BoxFit.cover -> 이미지의 크기를 컨테이너의 크기에 딱 맞게 설정

image 위젯의 설명은 이정도면 될 것 같고, 이제 indicator의 설명이다.

  • AnimatedSmoothIndicator -> indicator 선언
  • effect: JumpingDotEffect -> indicator의 애니메이션 효과 설정
  • dotHeight/dotWidth -> indicator의 점(dot) 크기 설정
  • activeDotColor -> 현재 활성화 된 dot 색상 설정
  • dotColor -> 활성화 되지 않은 dot 색상 설정
  • .withOpacity -> 색상 투명도 설정

이렇게 두 위젯을 모두 작성하고 나면, 이제 그 위젯을 겹쳐줘야 한다.
굳이 겹칠 필요가 없는 사람이라면 그냥 Column에 넣든 하면 되겠지만 나는 이미지 위에 인디케이터를 띄우고 싶었으므로 Flutter의 Stack을 사용했다.

Stack이란, Flutter에서 여러 위젯을 겹쳐서 배치할 수 있는 위젯이다.

Stack(alignment: Alignment.bottomCenter, children: <Widget>[
              CarouselSlider.builder(
                options: CarouselOptions(
                  initialPage: 0,
                  viewportFraction: 1,
                  enlargeCenterPage: true,
                  onPageChanged: (index, reason) => setState(() {
                    activeIndex = index;
                  }),
                ),
                itemCount: images.length,
                itemBuilder: (context, index, realIndex) {
                  final path = images[index];
                  return imageSlider(path, index);
                },
              ),
              Align(alignment: Alignment.bottomCenter, child: indicator())
            ])

코드에 대해 설명하자면,

  • initialPage -> 처음에 보여줄 페이지 설정
  • viewportFraction -> 활성화 된 페이지를 어떤 영역만큼 보여줄 건지 설정
    • 1로 설정하여 활성화 된 페이지가 위젯을 꽉 채움
  • enlargeCenterPage -> 활성화 된 페이지를 크게 보여줄 것인지 설정
    • true로 설정하여 크게 보여줌
  • onPageChanged -> 페이지가 변했을 때의 동작을 설정
  • itemCount -> 슬라이더에 들어갈 아이템의 개수 설정
  • itemBuilder -> index번째의 페이지에서 보여줄 View를 설정

이 정도로 정리할 수 있겠다.

나는 이미지 배열의 크기만큼 item 개수를 설정했고, 한 아이템이 위젯을 전부 채우도록 작성했다.

이렇게 작성을 마치면 아래와 같이 동작하는 걸 확인할 수 있다.

profile
정위블

0개의 댓글