[flutter] 플러터 앱에서 sticky 헤더를 사용한 명언 목록 앱 구현하기

소개

이번 포스트에서는 플러터(Flutter) 앱에서 sticky(고정) 헤더를 사용한 명언 목록 앱을 구현하는 방법에 대해 알아보겠습니다. sticky 헤더는 스크롤을 내렸을 때 항상 화면 상단에 고정되어 있는 헤더를 말합니다.

설치

먼저, 플러터 프로젝트를 생성합니다. 터미널에서 다음 명령어를 실행해주세요.

flutter create quote_app
cd quote_app

이후 pubspec.yaml 파일을 열고 sticky_headers 패키지를 추가해주세요. 아래와 같이 dependencies 섹션에 추가해주시면 됩니다.

dependencies:
  flutter:
    sdk: flutter
  sticky_headers: ^0.2.0

패키지를 추가한 후, 아래 명령어를 통해 패키지를 다운로드합니다.

flutter pub get

구현

플러터 앱의 주요 코드는 다음과 같습니다.

import 'package:flutter/material.dart';
import 'package:sticky_headers/sticky_headers.dart';

void main() {
  runApp(QuoteApp());
}

class QuoteApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Quote App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('명언 목록'),
        ),
        body: ListView.builder(
          itemCount: quotes.length,
          itemBuilder: (BuildContext context, int index) {
            return StickyHeader(
              header: Container(
                height: 50.0,
                color: Colors.blueGrey[700],
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  'Category ${quotes[index].category}',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              content: Column(
                children: quotes[index]
                    .quotes
                    .map((quote) => ListTile(
                          title: Text(quote),
                          subtitle: Text('Author: ${quote.author}'),
                        ))
                    .toList(),
              ),
            );
          },
        ),
      ),
    );
  }
}

class QuoteCategory {
  final String category;
  final List<Quote> quotes;

  QuoteCategory({required this.category, required this.quotes});
}

class Quote {
  final String quote;
  final String author;

  Quote({required this.quote, required this.author});
}

List<QuoteCategory> quotes = [
  QuoteCategory(
    category: '성공',
    quotes: [
      Quote(quote: '성공은 준비된 사람에게 온다.', author: '알버트 아인슈타인'),
      Quote(quote: '불가능은 나태한 자의 약자버전이다.', author: '암비션'),
    ],
  ),
  QuoteCategory(
    category: '사랑',
    quotes: [
      Quote(quote: '너의 전부는 내 전부이다.', author: '니체'),
      Quote(quote: '사랑은 심장으로 결정하지 않는다.', author: '엘레나 페란테'),
    ],
  ),
];

위 코드에서는 sticky_headers 패키지를 사용하여 sticky 헤더를 구현하였습니다. ListView.builder로 명언 목록을 구성하고, StickyHeader 위젯으로 각 카테고리별로 sticky 헤더를 생성하였습니다.

결론

이번 포스트에서는 플러터 앱에서 sticky 헤더를 사용한 명언 목록 앱을 구현하는 방법에 대해 알아보았습니다. sticky 헤더를 사용하면 사용자가 스크롤을 내리더라도 항상 헤더를 볼 수 있습니다. 이를 활용하여 다양한 앱을 개발해보세요!