BottomNavigationBarItemを3つ作成し、各アイコンをタップすると対象のWidgetを表示するようにコーディングしてみる。
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _selectedIndex = 0;
static const _pages =[
Scaffold(body: Center(child: Text('Home'))),
Scaffold(body: Center(child: Text('Article'))),
Scaffold(body: Center(child: Text('Settings'))),
];
void _onTap(final int index){
setState((){
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('MyApp'),),
body: _pages[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home',),
BottomNavigationBarItem(icon: Icon(Icons.article), label: 'Article',),
BottomNavigationBarItem(icon: Icon(Icons.settings_accessibility), label: 'Settings',),
],
currentIndex: _selectedIndex,
onTap: _onTap,
),
),
);
}
}
結果
下のアイコンをタップする都度、対象の文字列が表示されWidgetが切り替わっていることを確認できた。
