NavigationBar
為智慧手機經典介面,將 Button
放在底部方便使用者快速切換頁面。
Version
Flutter 3.24
Flutter
NavigationBar
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() => _Home();
}
class _Home extends State<Home> {
int _selectedIndex = 0;
static const List<Widget> navigationPages = [
Center(child: Text('Home')),
Center(child: Text('Search')),
Center(child: Text('Profile')),
];
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('NavigationBar'),
);
var navigationBar = NavigationBar(
selectedIndex: _selectedIndex,
onDestinationSelected: (int index) =>
setState(() => _selectedIndex = index),
destinations: const [
NavigationDestination(
icon: Icon(Icons.home),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.search),
label: 'Search',
),
NavigationDestination(
icon: Icon(Icons.person),
label: 'Profile',
),
],
);
return Scaffold(
appBar: appBar,
body: navigationPages[_selectedIndex],
bottomNavigationBar: navigationBar,
);
}
}
Line 11
int _selectedIndex = 0;
_selectedIndex
:儲存用戶所選擇的 index
Line 13
static const List<Widget> navigationPages = [
Center(child: Text('Home')),
Center(child: Text('Search')),
Center(child: Text('Profile')),
];
navigationPages
:定義每個NavigationButton
所對應的 page
Line 25
var navigationBar = NavigationBar(
selectedIndex: _selectedIndex,
onDestinationSelected: (int index) =>
setState(() => _selectedIndex = index),
destinations: const [
NavigationDestination(
icon: Icon(Icons.home),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.search),
label: 'Search',
),
NavigationDestination(
icon: Icon(Icons.person),
label: 'Profile',
),
],
)
NavigationBar
:建立NavigationBar
selectedIndex
:目前用戶所選擇的 index,綁定到_selectedIndex
stateonDestinationSelected
:當用戶按下不同NavigationButton
時所觸發的 eventdestinations
:定義NavigationButton
清單NavigationDestination
:定義NavigationButton
Conclusion
NavigationButton
為觀念上的名稱,Flutter 實際上NavigationDestination