Develop/Flutter

[Flutter] 플러터 Slivers 애니메이션 구현

JunJangE 2022. 2. 20. 16:19

이번에는 Slivers 애니메이션 효과에 대해서 알아보도록 하자.

Slivers는 화면 헤더를 동적으로 표현하고 헤더를 위로 스크롤했을 때, 헤더 하단 부분이 나오는 애니메이션이다.

당근 마켓, 번개장터 등 게시물이 있는 UI를 생각하면 이해하기 쉬울 것 같다.

코드를 작성하기 전에 간단하게 알아보면 CustomScrollView를 통해 body를 감싸게 된다. 그냥 Sliver를 사용하기 위한 ScrollView라고 생각하면 좋을 것 같다. CustomScrollView 안에는 SliverAppBar와 다양한 Sliver 위젯이 들어간다. SliverAppBar는 헤더 부분이 되고 Sliver 위젯은 헤더 하단 부분이 된다.

그럼 코드를 작성하면서 구현해보자.

코드

import 'package:flutter/material.dart';

class SliversScreen extends StatefulWidget {
  const SliversScreen({Key? key}) : super(key: key);

  @override
  _SliversScreenState createState() => _SliversScreenState();
}

class _SliversScreenState extends State<SliversScreen> {
  Widget build(BuildContext context) {
    return Scaffold(
      // ScrollView의 종류로 Sliver와 같이 사용된다.
      body: CustomScrollView(
        slivers: <Widget>[
          // appBar
          SliverAppBar(
            expandedHeight: 250.0, // appBar 높이
            pinned: true,
            floating: false,
            snap: false,
            // Sliver appBar를 설정
            flexibleSpace: FlexibleSpaceBar(
              title: Text('SliverAppBar'),
              centerTitle: true,
              background: FlutterLogo(),
            ),
          ),

          /*********************** body 부분 *************************/

          // Sliver 1
          // basic
          SliverFillRemaining(
            child: Center(child: Text("SliberAppBody")),
          ),

          // Sliver 2
          // Grid view
          SliverGrid(
            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 200.0, // Grid view 너비
              mainAxisSpacing: 10.0, // 행 간 거리
              crossAxisSpacing: 10.0, // 열 간 거리
            ),
            // 화면에 표시될 위젯을 설정
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Container(
                  alignment: Alignment.center,
                  color: Colors.green,
                  child: Text(
                    'Grid Item $index',
                    style: TextStyle(fontSize: 20),
                  ),
                );
              },
              childCount: 10,
            ),
          ),

          // Sliver 3
          // List view
          SliverFixedExtentList(
            itemExtent: 50.0,
            // 화면에 표시될 위젯을 설정
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return ListTile(
                  title: Text(
                    'List Item $index',
                    style: TextStyle(fontSize: 20),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

SliverAppBar

위에서부터 코드를 보게 되면 SliverAppBar를 통해 헤더 부분을 구현한 것을 확인할 수 있다.

SliverAppBar에는 appBar를 설정해주는 속성들이 있다.

expandedHeight 속성은 appBar의 높이를 설정하는 속성이다.

pinned 속성을 알아보면, 초기값은 false이며 스크롤을 내렸을 때 앱바를 사라지게 할 것인지, 사라지게 안 할 것인지를 설정하는 속성이다.

floating 속성을 알아보면, 초기값은 false이며 스크롤을 내린 후 올렸을 때 앱바가 천천히 나오게 할 것인지, 맨 위에서 나오게 할 것인지를 설정하는 속성이다.

snap 속성을 알아보면, 초기값은 false이며 floating과 함께 작성해야 한다. 구현되는 모습을 보면 쉽게 이해할 수 있다. snap은 floating과 기능이 비슷해 보이지만 차이점으로 스크롤을 내린 후 올렸을 때 앱바가 천천히 내려오는 것이 아닌 한 번에 내려오게 되는 것이다.

flexibleSpace는 appBar에 어떤 UI를 구현할 건지 설정하는 속성이다.

Sliver

다음으로 작성되는 부분은 SliverAppBar 하단 부분인 body 부분이다. body부분에는 다양한 Sliver 위젯 부분이 들어가게 된다. 우리는 그중에서 3가지 Sliver 위젯을 알아보도록 하자.

SliverFillRemaining

sliverFillRemaining 위젯은 그냥 스크롤 영역에 표시될 화면을 정의한 것이라고 이해하면 쉬울 것 같다.

SliverGrid

SliverGrid는 gridDelegate를 통해 Grid view 어떻게 나열할 것인지 설정하고 delegate를 통해 화면에 표시될 위젯을 설정한다. 

SliverFixedExtentList

SliverFixedExtentList는 itemExtent를 통해 List에 크기를 정하고 delegate를 통해 화면에 표시될 위젯을 설정한다.

위 코드를 모두 작성하고 실행하면 다음 영상과 같이 실행되는 것을 확인할 수 있다.

참고

 

Using slivers to achieve fancy scrolling

Where to find information on using slivers to implement fancy scrolling effects, like elastic scrolling, in Flutter.

docs.flutter.dev

 

[flutter] Sliver 설명 정리본 (Slivers explained - Making dynamic layouts)

Flutter공홈 기준으로 Development > UI > Advenced UI에서 소개되는 Slivers영상 3개와 함께 설명이 아주 잘 나와있습니다.slivers = 스크롤의 끝판왕

velog.io