ナビゲーションバー付きタブ
CoddyのFlutterジャーニー「リストと画面」セクションの一部。レッスン 23/33。
多くのアプリでは、画面下部のタブにメインページを配置しています。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は1つのタブで、アイコンとラベルがあります。selectedIndexは、どのタブが選択状態で強調表示されるかを示します。番号は0から数えます。タブがタップされると、onDestinationSelectedにそのインデックスが渡されます。
バー自体はタブを記憶しません。状態にindexを保持し、setStateで変更します。本文にはそのインデックスに対応するページが表示されます。この例では、ウィジェットのリストからpages[index]を表示します。
チャレンジ
簡単バーにはタブが3つありますが、タップしても何も起こりません。タップしたタブがハイライト表示され、そのページが表示されるように 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オンラインコンパイラ