Open1
FlutterのcurrentIndexはどう使うの?
currentIndex
は、Flutterの BottomNavigationBar
や CupertinoTabBar
などのウィジェットで使用されるプロパティです。これは、タブバー内の現在選択されているタブを示します。
具体的には、BottomNavigationBar
は画面の下部に表示されるナビゲーションバーで、異なるタブを選択するために使用されます。各タブは BottomNavigationBarItem
ウィジェットで構成されており、currentIndex
プロパティは現在選択されているタブのインデックスを示します。
以下は、BottomNavigationBar
を使用してタブバーを実装する例です。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
// タブを切り替えた時の処理
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BottomNavigationBar Example'),
),
body: Center(
child: Text('Current Tab: $_currentIndex'),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: onTabTapped, // タブがタップされた時の処理
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search'),
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
title: Text('Settings'),
),
],
),
);
}
}
この例では、BottomNavigationBar
が3つのタブを持ち、各タブは異なるアイコンとテキストを持ちます。currentIndex
は選択されているタブのインデックスを示し、onTabTapped
メソッドでタブがタップされた時に currentIndex
を更新します。選択されたタブの内容は、currentIndex
を参照して表示されています。