
Using Slivers to Achieve Fancy Scrolling in Flutter
01. 서론
1) 슬리버(Sliver)란 무엇인가?
슬리버(Sliver)는 Flutter에서 스크롤 가능한 영역의 일부로 동작하는 위젯을 의미합니다. 슬리버는 스크롤할 수 있는 다양한 형태의 콘텐츠를 만들 수 있으며, 다양한 스크롤 효과를 적용할 수 있는 유연성을 제공합니다. 일반적인 스크롤 위젯과는 달리, 슬리버는 레이아웃이나 콘텐츠를 동적으로 변화시킬 수 있어 더욱 정교한 스크롤 인터페이스를 구현할 수 있습니다.
2) 슬리버를 사용하는 이유
슬리버를 사용하는 주된 이유는 복잡한 스크롤 레이아웃을 쉽게 구현할 수 있기 때문입니다. 예를 들어, 스크롤 시 헤더가 축소되거나 확장되는 효과, 스크롤 위치에 따라 다양한 레이아웃을 동적으로 변경하는 등의 기능을 슬리버를 통해 간편하게 구현할 수 있습니다. 슬리버는 효율적인 메모리 사용을 가능하게 하여 성능 최적화에도 기여합니다.
02. SliverAppBar
1) SliverAppBar의 소개
SliverAppBar는 스크롤할 때 헤더가 축소되거나 확장되는 애니메이션 효과를 제공하는 위젯입니다. 이를 통해 사용자는 인터페이스를 더 직관적이고 시각적으로 매력적으로 만들 수 있습니다. SliverAppBar는 주로 CustomScrollView와 함께 사용되며, 스크롤 시 앱바가 자동으로 축소되거나 확장되는 효과를 제공합니다.
2) SliverAppBar를 사용한 예제 코드
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              expandedHeight: 200.0,
              floating: false,
              pinned: true,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('SliverAppBar 예제'),
                background: Image.network(
                  'https://flutter.dev/images/catalog-widget-placeholder.png',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return ListTile(
                    title: Text('Item $index'),
                  );
                },
                childCount: 50,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
        
위 코드를 실행하면, 사용자는 화면을 스크롤할 때 SliverAppBar가 부드럽게 축소되고, 리스트 항목이 나타나는 것을 볼 수 있습니다. 이 효과는 앱의 사용자 경험을 향상시키고, 시각적으로 매력적인 인터페이스를 제공합니다.
03. SliverList와 SliverGrid
1) SliverList와 SliverGrid의 소개
SliverList와 SliverGrid는 각각 리스트와 그리드를 스크롤 가능한 형태로 배치할 수 있는 슬리버 위젯입니다. SliverList는 수직 방향으로 아이템을 나열하는 리스트를 만들 수 있고, SliverGrid는 격자 형태로 아이템을 배치합니다. 두 위젯 모두 대량의 데이터나 동적 데이터를 효율적으로 표시하는 데 유용합니다.
2) SliverList와 SliverGrid를 사용한 예제 코드
SliverList 예제:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              expandedHeight: 200.0,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('SliverList 예제'),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return ListTile(
                    title: Text('Item $index'),
                  );
                },
                childCount: 20,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
        
SliverGrid 예제:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              expandedHeight: 200.0,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('SliverGrid 예제'),
              ),
            ),
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return Container(
                    color: index.isEven ? Colors.blue : Colors.green,
                    child: Center(child: Text('Grid Item $index')),
                  );
                },
                childCount: 20,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
        
위 코드를 실행하면, CustomScrollView 내에 SliverAppBar가 위치하며, 그 아래에 SliverList 또는 SliverGrid가 스크롤 가능한 형태로 배치됩니다. 사용자는 스크롤을 통해 리스트 또는 그리드의 모든 항목을 볼 수 있습니다.
04. CustomScrollView
1) CustomScrollView의 소개
CustomScrollView는 여러 슬리버를 조합하여 복잡한 스크롤 레이아웃을 만들 수 있는 위젯입니다. 슬리버를 사용하여 다양한 스크롤 효과를 적용할 수 있으며, 필요한 대로 레이아웃을 구성할 수 있습니다. CustomScrollView는 여러 종류의 슬리버를 포함할 수 있어 유연하고 강력한 스크롤 인터페이스를 제공합니다.
2) 여러 슬리버를 조합한 레이아웃 구현
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              expandedHeight: 200.0,
              floating: true,
              pinned: true,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('CustomScrollView 예제'),
                background: Image.network(
                  'https://flutter.dev/images/catalog-widget-placeholder.png',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return ListTile(
                    title: Text('List Item $index'),
                  );
                },
                childCount: 10,
              ),
            ),
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return Container(
                    color: index.isEven ? Colors.blue : Colors.green,
                    child: Center(child: Text('Grid Item $index')),
                  );
                },
                childCount: 10,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
        
위 코드를 실행하면, 사용자는 CustomScrollView 내에서 다양한 슬리버 조합을 통해 리스트와 그리드를 스크롤할 수 있습니다. 이는 복잡한 레이아웃을 효율적으로 구성하고, 다양한 스크롤 효과를 제공하는 데 유용합니다.
05. 다양한 스크롤링 효과 구현
1) 탄력적 스크롤링
탄력적 스크롤링(Elastic Scrolling)은 사용자가 리스트의 끝까지 스크롤할 때 탄력적으로 반응하는 효과를 제공합니다. 이는 기본적으로 ListView와 같은 스크롤 가능한 위젯에서 제공됩니다. 이 효과는 자연스럽고 직관적인 사용자 경험을 제공합니다.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            Container(height: 100, color: Colors.red),
            Container(height: 100, color: Colors.blue),
            Container(height: 100, color: Colors.green),
            Container(height: 100, color: Colors.yellow),
            Container(height: 100, color: Colors.orange),
          ],
        ),
      ),
    );
  }
}
        
2) 패럴랙스 스크롤링
패럴랙스 스크롤링(Parallax Scrolling)은 배경 이미지가 콘텐츠보다 느리게 스크롤되는 효과를 제공합니다. 이를 통해 시각적으로 매력적인 UI를 만들 수 있습니다.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              expandedHeight: 200.0,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('패럴랙스 스크롤링'),
                background: Image.network(
                  'https://flutter.dev/images/catalog-widget-placeholder.png',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return ListTile(
                    title: Text('Item $index'),
                  );
                },
                childCount: 20,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
        
06. 결론
1) 슬리버를 사용한 스크롤링의 장점
슬리버를 사용하면 Flutter에서 다양한 스크롤링 효과와 복잡한 레이아웃을 효율적으로 구현할 수 있습니다. 슬리버를 통해 다음과 같은 장점을 얻을 수 있습니다:
- 유연성: 슬리버를 사용하여 커스텀 스크롤 효과를 적용할 수 있습니다.
 - 성능 최적화: 필요한 항목만 동적으로 생성하여 메모리 사용을 최적화할 수 있습니다.
 - 다양한 레이아웃: CustomScrollView와 다양한 슬리버를 조합하여 복잡한 스크롤 레이아웃을 구성할 수 있습니다.
 
2) 추가 학습 자료와 참고 링크
Flutter에서 슬리버와 스크롤링을 더 깊이 이해하고자 하는 개발자를 위해 추가 학습 자료와 참고 링크를 제공합니다.
관련된 다른 글도 읽어보시길 추천합니다
2024.08.02 - [Study] - 36. Flutter에서 일정 간격이 있는 리스트 만들기 | Flutter
2024.08.02 - [Study] - 35. Flutter로 다양한 유형의 아이템이 포함된 리스트 만들기 | Flutter
2024.07.31 - [Study] - 34. Flutter GridView로 그리드 리스트 구현하기 | Flutter
읽어주셔서 감사합니다
공감은 힘이 됩니다
:)
'Study' 카테고리의 다른 글
| 41. 패럴랙스 스크롤: 시각적 효과 극대화하기 | Flutter (0) | 2024.08.10 | 
|---|---|
| 40. 스크롤 가능한 리스트 위에 플로팅 앱바를 배치하기 | Flutter (0) | 2024.08.09 | 
| 38. 스크롤링 개요: 다양한 스크롤링 방법과 위젯 소개 | Flutter (0) | 2024.08.07 | 
| 37. Flutter에서 긴 리스트를 효율적으로 처리하는 방법 | Flutter (0) | 2024.08.06 | 
| 36. Flutter에서 일정 간격이 있는 리스트 만들기 | Flutter (0) | 2024.08.05 |