早速、コードに進みましょう。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bottom Navigation Bar',
theme: ThemeData(
primaryColor: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
final List<Widget> _pages = [
HomePage(),
SearchPage(),
ProfilePage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bottom Navigation Bar'),
),
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Home Page'),
);
}
}
class SearchPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Search Page'),
);
}
}
class ProfilePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Profile Page'),
);
}
}
上の例では、MyHomePage
というウィジェットを作成しましたStatefulWidget
。MyHomePage
下部のナビゲーション バーと関連ページのコンテンツが含まれます。BottomNavigationBar
およびプロパティを通じてcurrentIndex
、現在選択されているナビゲーション項目を制御し、onTap
コールバックの状態を更新できます。
items
プロパティでは3 つを設定しBottomNavigationBarItem
、それぞれにアイコンとラベルを付けます。ユーザーがナビゲーション項目を切り替えると、onTap
コールバックによってcurrentIndex
値が更新され、その値が対応するページの表示に使用されます。
この例では、ニーズに応じてこれらのページのコンテンツをカスタマイズできる3 つの単純なページ ( HomePage
、 、SearchPage
および) を作成しました。ProfilePage
この例がお役に立てば幸いです。