【Flutterやろうよ!】初級編 その6〜ボトムメニュー その2〜
今回は、BottomNavigationBarで画面の切り替えをしたいと思います!
まずは3つ画面を用意しておきます。
import 'package:flutter/material.dart';
class Screen01 extends StatelessWidget {
const Screen01({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ホーム'),
),
body: Center(
child: Text(
'ホーム画面',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
);
}
}
簡単にこんな感じの画面を3つ(タブの数だけ)用意します。
次に、タブ画面のあるクラスに表示したい画面のリストを作成します。
final _screens = [
const Screen01(),
const Screen02(),
const Screen03(),
];
BottomNavigationBarのonTapで切り替わったタブのindexが取得できるので、
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
こんな感じでindexを書き換えているかと思います。
では画面の切り替えはどうするかといいますと。
body: _screens[_currentIndex],
Scaffoldのbodyに選択中のindexに該当する画面を渡してあげます。
全体のコードはこうなります。
import 'package:blog_sample/views/sample05/screen01.dart';
import 'package:blog_sample/views/sample05/screen02.dart';
import 'package:blog_sample/views/sample05/screen03.dart';
import 'package:flutter/material.dart';
class Sample05 extends StatefulWidget {
const Sample05({super.key});
@override
State createState() => _State();
}
class _State extends State<Sample05> {
final _screens = [
const Screen01(),
const Screen02(),
const Screen03(),
];
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: _screens[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
currentIndex: _currentIndex,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
activeIcon: Icon(Icons.home, color: Colors.blue),
label: 'ホーム',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
activeIcon: Icon(
Icons.business,
color: Colors.blue,
),
label: 'ビジネス',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
activeIcon: Icon(Icons.school, color: Colors.blue),
label: '学校',
),
],
),
);
}
}
これで画面の切り替えができるようになりましたね!
これでいい感じの複数画面をタブで切り替えるアプリが作れるようになりました!
中の画面はお好きなように作ってみてください!