點燈坊

失くすものさえない今が強くなるチャンスよ

NavigationBar 實現底部 Button 切換

Sam Xiao's Avatar 2024-10-29

NavigationBar 為智慧手機經典介面,將 Button 放在底部方便使用者快速切換頁面。

Version

Flutter 3.24

Flutter

navigationbar01

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 state
    • onDestinationSelected:當用戶按下不同 NavigationButton 時所觸發的 event
    • destinations:定義 NavigationButton 清單
      • NavigationDestination:定義 NavigationButton

Conclusion

  • NavigationButton 為觀念上的名稱,Flutter 實際上 NavigationDestination