BLOG
マテリアルデザイン3(Material Design3)シリーズ NavigationBar
Material design 3
2024.06.19
2024.06.24
1. 今回のテーマ
今回のテーマは、NavigationBarです。
BottomNavigationBarと類似していますが、別のコンポーネントです。違いはデザイン性のみです。
NavigationBarは、Material Design 3 ComponentのNavigationに分類される画面下部にナビゲーションを表示するコンポーネントです。主に3〜5個のメニューを表示する場合に利用されます。6個以上のメニューを表示したい場合は、Navigation drawerを利用してください。
詳細はこちらを御覧ください。
https://m3.material.io/components/navigation-bar/overview
2. サンプルコード
この例は、画面下部に5つのメニューを表示するサンプルです。
bottomNavigationBarに、NavigationBarを設定します。
import 'package:flutter/material.dart';
class BottomNavigationScreen extends StatefulWidget {
const BottomNavigationScreen({super.key});
@override
State<BottomNavigationScreen> createState() => _TabBarScreenState();
}
class _TabBarScreenState extends State<BottomNavigationScreen> {
final _screens = [
Scaffold(
appBar: AppBar(
title: const Text('ホーム'),
),
body: Container(),
),
Scaffold(
appBar: AppBar(
title: const Text('検索'),
),
body: Container(),
),
Scaffold(
appBar: AppBar(
title: const Text('お気に入り'),
),
body: Container(),
),
Scaffold(
appBar: AppBar(
title: const Text('メッセージ'),
),
body: Container(),
),
Scaffold(
appBar: AppBar(
title: const Text('その他'),
),
body: Container(),
),
];
final _barItems = const [
NavigationDestination(
icon: Icon(Icons.home),
selectedIcon: Icon(
Icons.home,
color: Colors.white,
),
label: 'ホーム',
tooltip: 'ホーム',
),
NavigationDestination(
icon: Icon(Icons.search_rounded),
selectedIcon: Icon(
Icons.search_rounded,
color: Colors.white,
),
label: '検索',
tooltip: '検索',
),
NavigationDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(
Icons.favorite_border,
color: Colors.white,
),
label: 'お気に入り',
tooltip: 'お気に入り',
),
NavigationDestination(
icon: Icon(Icons.notifications),
selectedIcon: Icon(
Icons.notifications,
color: Colors.white,
),
label: 'お知らせ',
tooltip: 'お知らせ',
),
NavigationDestination(
icon: Icon(Icons.more_vert),
selectedIcon: Icon(
Icons.more_vert,
color: Colors.white,
),
label: 'その他',
tooltip: 'その他',
),
];
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: _screens[_selectedIndex],
bottomNavigationBar: NavigationBar(
onDestinationSelected: (index) => _onDestinationSelected(index),
indicatorColor: Colors.black26,
selectedIndex: _selectedIndex,
destinations: _barItems,
),
);
}
void _onDestinationSelected(int index) {
setState(() {
_selectedIndex = index;
});
}
}
3. カスタマイズ
3.1. テーマの変更
背景色を変更する場合は、backgroundColorに背景色を設定します。また、選択中アイコンのカラーを変更する場合は、indicatorColorに所定の色を指定します。
NavigationBar(
backgroundColor: Colors.lightBlue,
onDestinationSelected: (index) => _onDestinationSelected(index),
indicatorColor: Colors.white,
selectedIndex: _selectedIndex,
destinations: _barItems,
),
4. まとめ
今回は、NavigationBarをご紹介しました。BottomNavigationBarと類似していますが、Material Design3に準拠する場合は、NavigationBarを利用することをオススメします。
また、メニューが6個以上の場合は、Navigation drawerの利用を検討してください。