내비게이션 바가 있는 탭
Coddy Flutter 여정의 목록과 화면 섹션에 포함된 레슨. 33개 중 23번째.
많은 앱은 화면 하단의 탭에 주요 페이지를 배치합니다. NavigationBar가 탭을 그리며, 이를 Scaffold의 bottomNavigationBar:에 지정합니다.
NavigationBar(
selectedIndex: index,
onDestinationSelected: (int i) {
setState(() {
index = i;
});
},
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
)각 NavigationDestination은 아이콘과 라벨이 있는 탭 하나입니다. selectedIndex는 0부터 세어 어떤 탭이 강조 표시되는지 나타냅니다. 탭을 누르면 onDestinationSelected에 해당 탭의 인덱스가 전달됩니다.
탐색 바는 탭을 자체적으로 기억하지 않습니다. 상태에 index를 저장하고 setState로 변경해야 합니다. 본문에는 해당 인덱스의 페이지가 표시됩니다. 여기서는 위젯 목록의 pages[index]입니다.
챌린지
쉬움탭이 세 개 있는 막대지만, 탭해도 아무 동작도 하지 않습니다. 탭한 항목이 강조 표시되고 해당 페이지가 표시되도록 onDestinationSelected:를 추가하세요. Favorites에는 Favorites page를, Settings에는 Settings page를 표시하세요.
직접 해보기
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int index = 0;
final List<Widget> pages = const [
Center(child: Text('Home page')),
Center(child: Text('Favorites page')),
Center(child: Text('Settings page')),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('My App')),
body: pages[index],
bottomNavigationBar: NavigationBar(
selectedIndex: index,
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.favorite), label: 'Favorites'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
목록과 화면의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러