플러터는 굉장히 강력한 UI 프레임워크이며, 많은 개발자들이 플러터를 사용하여 멋진 앱을 개발하고 있습니다. 이번에는 플러터를 사용하여 헤더가 붙는(sticky) 탭 바를 구현하는 방법에 대해 알아보겠습니다.
1. 필요한 패키지 import하기
우선, sticky 헤더와 탭 바를 구현하기 위해 다음 두 개의 패키지를 import해야 합니다.
import 'package:flutter/material.dart';
import 'package:sticky_headers/sticky_headers.dart';
2. StickyHeader를 사용하여 헤더 생성하기
StickyHeader 위젯은 리스트나 그리드뷰와 같은 스크롤 가능한 위젯의 헤더에 sticky 속성을 추가할 수 있게 해줍니다. 이를 사용하여 헤더 위젯을 생성합니다.
StickyHeader(
header: Container(
height: 50.0,
color: Colors.blue,
alignment: Alignment.center,
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'헤더',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
content: ListView(
children: [
ListTile(
title: Text('리스트 아이템 1'),
),
ListTile(
title: Text('리스트 아이템 2'),
),
//...
],
),
);
위 코드에서는 StickyHeader 위젯을 사용하여 헤더와 내용을 구성하고 있습니다. header 속성에는 헤더 위젯을, content 속성에는 내용 위젯(여기서는 ListView)을 설정합니다.
3. TabBar 구현하기
이제 헤더에 TabBar를 추가해보겠습니다. TabBar는 다른 탭 간의 전환 기능을 제공하는 위젯입니다.
DefaultTabController(
length: 2,
child: Scaffold(
body: StickyHeader(
header: TabBar(
tabs: [
Tab(text: '탭 1'),
Tab(text: '탭 2'),
],
),
content: TabBarView(
children: [
ListView( // 탭 1의 내용
children: [
ListTile(
title: Text('탭 1 - 리스트 아이템 1'),
),
ListTile(
title: Text('탭 1 - 리스트 아이템 2'),
),
//...
],
),
ListView( // 탭 2의 내용
children: [
ListTile(
title: Text('탭 2 - 리스트 아이템 1'),
),
ListTile(
title: Text('탭 2 - 리스트 아이템 2'),
),
//...
],
),
],
),
),
),
);
위 코드에서는 DefaultTabController와 Scaffold를 사용하여 TabBar와 TabBarView를 구현하고 있습니다.
TabBar는 tabs 속성에 Tab 위젯들을 설정하여 탭을 생성하고, TabBarView는 children 속성에 각 탭의 내용 위젯(ListView)들을 설정합니다.
4. 완성된 코드 예시
위에서 보여준 코드를 합쳐서 완성된 예시를 살펴보겠습니다.
import 'package:flutter/material.dart';
import 'package:sticky_headers/sticky_headers.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sticky Header TabBar Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
body: StickyHeader(
header: TabBar(
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
],
),
content: TabBarView(
children: [
ListView(
children: [
ListTile(
title: Text('Tab 1 - List Item 1'),
),
ListTile(
title: Text('Tab 1 - List Item 2'),
),
],
),
ListView(
children: [
ListTile(
title: Text('Tab 2 - List Item 1'),
),
ListTile(
title: Text('Tab 2 - List Item 2'),
),
],
),
],
),
),
),
);
}
}
위 코드를 실행하면 헤더가 sticky 속성을 가진 탭 바가 생성되고, 탭을 전환할 때마다 해당 탭의 내용이 나타납니다.
이와 같이 플러터를 사용하여 sticky 헤더가 있는 탭 바를 구현할 수 있습니다. 플러터의 다양한 위젯과 패키지를 활용하여 멋진 사용자 경험을 만들어보세요!